Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

SSM (#47)

LuckyIYI8b4704c61606
diff --git a/Cargo.lock b/Cargo.lock
index 43787a2a4..d0097c700 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -317,7 +317,7 @@ checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
[[package]]
name = "cli"
-version = "0.1.5"
+version = "0.1.6"
dependencies = [
"clap",
"console 0.16.0",
@@ -2640,7 +2640,7 @@ dependencies = [
[[package]]
name = "uzu"
-version = "0.1.5"
+version = "0.1.6"
dependencies = [
"bitflags 2.9.4",
"bytemuck",
diff --git a/Cargo.toml b/Cargo.toml
index 59248de2d..7f64a606a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ members = ["crates/cli", "crates/uzu"]
resolver = "3"
[workspace.package]
-version = "0.1.5"
+version = "0.1.6"
edition = "2024"
license = "MIT"
authors = ["Mirai Tech <https://trymirai.com>"]
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index 218fbe6d2..e22c69ed7 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "cli"
-version = "0.1.5"
+version = "0.1.6"
edition = "2024"
[[bin]]
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index 6d33165ee..800a969d4 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "uzu"
-version = "0.1.5"
+version = "0.1.6"
edition = "2024"
build = "build.rs"
diff --git a/crates/uzu/src/backends/metal/executable_builder/decoder_executables.rs b/crates/uzu/src/backends/metal/executable_builder/decoder_executables.rs
index ed02cc591..40a4b83a2 100644
--- a/crates/uzu/src/backends/metal/executable_builder/decoder_executables.rs
+++ b/crates/uzu/src/backends/metal/executable_builder/decoder_executables.rs
@@ -15,7 +15,7 @@ use crate::{
},
kernel::{RMSNormKernelEncodable, RopeKernelEncodable},
},
- config::decoder::DecoderConfig,
+ config::{DecoderConfig, DecoderLayerType, decoder_layer::MixerConfig},
parameters::ParameterTree,
};
@@ -24,7 +24,7 @@ pub struct DecoderExecutables {
pub layers: Box<[LayerExecutables]>,
pub norm: Box<dyn EncodableWithState>,
pub readout: Box<dyn EncodableWithState>,
- pub global_rope: Rc<Box<dyn EncodableWithState>>,
+ pub global_rope: Option<Rc<Box<dyn EncodableWithState>>>,
pub local_rope: Option<Rc<Box<dyn EncodableWithState>>>,
}
@@ -39,53 +39,95 @@ impl DecoderExecutables {
&decoder_config,
&mtl_context,
&compilation_config.descriptor_general,
+ decoder_weight_loader,
);
let readout = readout_block(
&decoder_config,
&mtl_context,
&compilation_config.descriptor_general,
+ decoder_weight_loader,
);
- let global_rope = Self::create_rope_block(
- &mtl_context,
- &decoder_config,
- RopeType::Global,
- );
+ let attention_data_type = Self::attention_data_type(&decoder_config);
+ let norm_reference_layer = decoder_config
+ .layer_configs
+ .as_ref()
+ .map(|configs| &configs[0])
+ .unwrap_or(&decoder_config.layer_config);
+ let norm_data_type: DataType = match &norm_reference_layer.mixer_config
+ {
+ MixerConfig::Attention(attention_config) => attention_config
+ .qkv_projection_config
+ .activation_precision()
+ .into(),
+ MixerConfig::Mamba(mamba_config) => {
+ mamba_config.in_projection_config.activation_precision().into()
+ },
+ };
+
+ let global_rope = if decoder_config.global_rope_config.is_some() {
+ attention_data_type.as_ref().map(|data_type| {
+ Self::create_rope_block(
+ &mtl_context,
+ (*data_type).into(),
+ RopeType::Global,
+ )
+ })
+ } else {
+ None
+ };
- let local_rope: Option<Rc<Box<dyn EncodableWithState>>>;
- if let Some(_) = &decoder_config.local_rope_config {
- local_rope = Some(Self::create_rope_block(
- &mtl_context,
- &decoder_config,
- RopeType::Local,
- ));
+ let local_rope = if decoder_config.local_rope_config.is_some() {
+ attention_data_type.as_ref().map(|data_type| {
+ Self::create_rope_block(
+ &mtl_context,
+ (*data_type).into(),
+ RopeType::Local,
+ )
+ })
} else {
- local_rope = None;
- }
+ None
+ };
let model_shape = ModelShape::from_decoder_config(&decoder_config);
- let sliding_window_sizes = model_shape.sliding_window_length_per_layer;
-
- let intermediate_data_type: DataType = decoder_config
- .layer_config
- .attention_config
- .qkv_projection_config
- .activation_precision()
- .into();
+ let sliding_window_sizes =
+ model_shape.sliding_window_length_per_layer.clone();
let layers = (0..decoder_config.num_layers)
.map(|layer_index| {
- let mut rope = global_rope.clone();
- if let (Some(_), Some(local_rope_block)) =
- (sliding_window_sizes[layer_index], local_rope.clone())
- {
- rope = local_rope_block;
- }
+ let layer_config = decoder_config
+ .layer_configs
+ .as_ref()
+ .map(|configs| &configs[layer_index])
+ .unwrap_or(&decoder_config.layer_config);
+ let layer_type = model_shape.layer_type(layer_index);
+ let rope_for_layer = match layer_type {
+ DecoderLayerType::Transformer => {
+ let mut rope_block = global_rope.clone().expect(
+ "Global rope missing for transformer layer",
+ );
+ if let (Some(_), Some(local_rope_block)) = (
+ sliding_window_sizes[layer_index],
+ local_rope.clone(),
+ ) {
+ rope_block = local_rope_block;
+ }
+ Some(rope_block)
+ },
+ DecoderLayerType::StateSpace {
+ ..
+ } => None,
+ };
+
+ let layer_loader = decoder_weight_loader
+ .subtree(&format!("layers.{}", layer_index))
+ .unwrap();
LayerExecutables::new(
&mtl_context,
- &decoder_config.layer_config,
+ layer_config,
+ layer_type,
compilation_config.clone(),
layer_index,
decoder_config.model_dim,
@@ -94,10 +136,8 @@ impl DecoderExecutables {
decoder_config.head_dim,
decoder_config.num_groups,
decoder_config.attention_scale,
- &decoder_weight_loader
- .subtree(&format!("layers.{}", layer_index))
- .unwrap(),
- rope,
+ &layer_loader,
+ rope_for_layer,
)
})
.collect::<Vec<_>>();
@@ -105,7 +145,7 @@ impl DecoderExecutables {
let norm_block: Box<dyn EncodableWithState> = Box::new(
RMSNormKernelEncodable::new(
&mtl_context,
- intermediate_data_type,
+ norm_data_type,
decoder_config.output_norm_config.clone(),
ArrayId::Main,
ArrayId::Main,
@@ -126,23 +166,31 @@ impl DecoderExecutables {
fn create_rope_block(
mtl_context: &MTLContext,
- decoder_config: &DecoderConfig,
+ kernel_data_type: KernelDataType,
rope_type: RopeType,
) -> Rc<Box<dyn EncodableWithState>> {
- let intermediate_data_type: DataType = decoder_config
- .layer_config
- .attention_config
- .qkv_projection_config
- .activation_precision()
- .into();
- let kernel_data_type: KernelDataType = intermediate_data_type.into();
-
let rotation: Box<dyn EncodableWithState> = Box::new(
RopeKernelEncodable::new(mtl_context, kernel_data_type, rope_type)
.expect("Failed to create RopeKernelEncodable"),
);
return Rc::new(rotation);
}
+
+ fn attention_data_type(decoder_config: &DecoderConfig) -> Option<DataType> {
+ (0..decoder_config.num_layers).find_map(|layer_index| {
+ let layer_config = decoder_config
+ .layer_configs
+ .as_ref()
+ .map(|configs| &configs[layer_index])
+ .unwrap_or(&decoder_config.layer_config);
+ layer_config.attention_config().map(|attention_config| {
+ attention_config
+ .qkv_projection_config
+ .activation_precision()
+ .into()
+ })
+ })
+ }
}
impl EncodableWithState for DecoderExecutables {
@@ -158,6 +206,10 @@ impl EncodableWithState for DecoderExecutables {
layer.encode(state, command_buffer, parameters);
}
+ if state.is_prefilling() {
+ return;
+ }
+
self.norm.encode(state, command_buffer, parameters);
if let Some(traces) = state.traces.clone() {
state
diff --git a/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs b/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
index 21575ac3b..98e26526f 100644
--- a/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
+++ b/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
@@ -14,11 +14,15 @@ use crate::{
transformer_layer,
},
kernel::{
- AttentionKernelEncodable, KernelDataType, QKNormKernelEncodable,
- RMSNormKernelEncodable, TensorAddSwap, TensorCopy,
+ AttentionKernelEncodable, KernelDataType, MambaMixerEncodable,
+ QKNormKernelEncodable, RMSNormKernelEncodable, TensorAddSwap,
+ TensorCopy,
},
},
- config::decoder_layer::DecoderLayerConfig,
+ config::{
+ DecoderLayerType,
+ decoder_layer::{DecoderLayerConfig, MixerConfig},
+ },
parameters::ParameterTree,
};
@@ -26,11 +30,7 @@ pub struct LayerExecutables {
pub layer_index: usize,
pub copy_main_to_shortcut: Box<dyn EncodableWithState>,
pub pre_attention_norm: Box<dyn EncodableWithState>,
- pub qkv_projection: Box<dyn EncodableWithState>,
- pub qk_norm: Option<Box<dyn EncodableWithState>>,
- pub rope: Rc<Box<dyn EncodableWithState>>,
- pub attention: Box<dyn EncodableWithState>,
- pub out_projection: Box<dyn EncodableWithState>,
+ pub(crate) mixer: MixerExecutables,
pub post_attention_norm: Option<Box<dyn EncodableWithState>>,
pub main_shortcut_add_swap: Box<dyn EncodableWithState>,
pub pre_mlp_norm: Box<dyn EncodableWithState>,
@@ -38,10 +38,25 @@ pub struct LayerExecutables {
pub post_mlp_norm: Option<Box<dyn EncodableWithState>>,
}
+pub(crate) enum MixerExecutables {
+ Attention {
+ qkv_projection: Box<dyn EncodableWithState>,
+ qk_norm: Option<Box<dyn EncodableWithState>>,
+ rope: Rc<Box<dyn EncodableWithState>>,
+ attention: Box<dyn EncodableWithState>,
+ out_projection: Box<dyn EncodableWithState>,
+ },
+ StateSpace {
+ mixer: Box<dyn EncodableWithState>,
+ },
+}
+
impl LayerExecutables {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
mtl_context: &MTLContext,
layer_config: &DecoderLayerConfig,
+ layer_type: &DecoderLayerType,
compilation_config: Rc<CompilationConfig>,
layer_index: usize,
model_dim: usize,
@@ -51,14 +66,19 @@ impl LayerExecutables {
num_groups: usize,
attention_scale: Option<f32>,
decoder_layer_loader: &ParameterTree<Rc<MTLContext>>,
- rope: Rc<Box<dyn EncodableWithState>>,
+ rope: Option<Rc<Box<dyn EncodableWithState>>>,
) -> Self {
autoreleasepool(|_| {
- let intermediate_data_type: DataType = layer_config
- .attention_config
- .qkv_projection_config
- .activation_precision()
- .into();
+ let intermediate_data_type: DataType =
+ match &layer_config.mixer_config {
+ MixerConfig::Attention(attention) => attention
+ .qkv_projection_config
+ .activation_precision()
+ .into(),
+ MixerConfig::Mamba(mamba) => {
+ mamba.in_projection_config.activation_precision().into()
+ },
+ };
let kernel_data_type: KernelDataType =
intermediate_data_type.into();
@@ -78,71 +98,115 @@ impl LayerExecutables {
layer_config.pre_attention_norm_config.clone(),
ArrayId::Main,
ArrayId::Main,
- &decoder_layer_loader
- .subtree("pre_attention_norm")
- .unwrap(),
+ &decoder_layer_loader.subtree("pre_mixer_norm").unwrap(),
)
.expect("Failed to create RMS norm kernel"),
);
- let qkv_projection = transformer_layer::linear_block(
- &layer_config.attention_config.qkv_projection_config,
- layer_config.attention_config.has_qkv_biases,
- model_dim,
- [
- num_heads * head_dim,
- num_groups * head_dim,
- num_groups * head_dim,
- ],
- mtl_context,
- &decoder_layer_loader
- .subtree("attention.qkv_projection")
- .unwrap(),
- ArrayId::Main,
- ArrayId::QKV,
- &compilation_config.descriptor_mlp,
- );
+ let mixer = match &layer_config.mixer_config {
+ MixerConfig::Attention(attention_config) => {
+ let rope_block = rope
+ .clone()
+ .expect("RoPE encoder missing for attention layer");
- let qk_norm: Option<Box<dyn EncodableWithState>> = if layer_config
- .attention_config
- .query_norm_config
- .is_some()
- || layer_config.attention_config.key_norm_config.is_some()
- {
- match QKNormKernelEncodable::new(
- mtl_context,
- intermediate_data_type,
- layer_config.attention_config.query_norm_config.clone(),
- layer_config.attention_config.key_norm_config.clone(),
- ArrayId::QKV,
- &decoder_layer_loader.subtree("attention").unwrap(),
- num_heads, // num_q_heads
- num_groups, // num_kv_heads
- head_dim,
- ) {
- Ok(qk_norm) => Some(Box::new(qk_norm)),
- Err(e) => panic!(
- "Failed to create QK norm kernel for layer {}: {:?}",
- layer_index, e
- ),
- }
- } else {
- None
- };
+ let qkv_projection = transformer_layer::linear_block(
+ &attention_config.qkv_projection_config,
+ attention_config.has_qkv_biases,
+ model_dim,
+ [
+ num_heads * head_dim,
+ num_groups * head_dim,
+ num_groups * head_dim,
+ ],
+ mtl_context,
+ &decoder_layer_loader
+ .subtree("mixer.qkv_projection")
+ .unwrap(),
+ ArrayId::Main,
+ ArrayId::QKV,
+ &compilation_config.descriptor_mlp,
+ );
- let out_projection = transformer_layer::linear_block(
- &layer_config.attention_config.out_projection_config,
- layer_config.attention_config.has_out_biases,
- num_heads * head_dim,
- [model_dim],
- mtl_context,
- &decoder_layer_loader
- .subtree("attention.out_projection")
- .unwrap(),
- ArrayId::AttentionOutput,
- ArrayId::Main,
- &compilation_config.descriptor_mlp,
- );
+ let qk_norm: Option<Box<dyn EncodableWithState>> =
+ if attention_config.query_norm_config.is_some()
+ || attention_config.key_norm_config.is_some()
+ {
+ match QKNormKernelEncodable::new(
+ mtl_context,
+ intermediate_data_type,
+ attention_config.query_norm_config.clone(),
+ attention_config.key_norm_config.clone(),
+ ArrayId::QKV,
+ &decoder_layer_loader.subtree("mixer").unwrap(),
+ num_heads,
+ num_groups,
+ head_dim,
+ ) {
+ Ok(qk_norm) => Some(Box::new(qk_norm)
+ as Box<dyn EncodableWithState>),
+ Err(e) => panic!(
+ "Failed to create QK norm kernel for layer {}: {:?}",
+ layer_index, e
+ ),
+ }
+ } else {
+ None
+ };
+
+ let out_projection = transformer_layer::linear_block(
+ &attention_config.out_projection_config,
+ attention_config.has_out_biases,
+ num_heads * head_dim,
+ [model_dim],
+ mtl_context,
+ &decoder_layer_loader
+ .subtree("mixer.out_projection")
+ .unwrap(),
+ ArrayId::AttentionOutput,
+ ArrayId::Main,
+ &compilation_config.descriptor_mlp,
+ );
+
+ let attention = Box::new(
+ AttentionKernelEncodable::new(
+ mtl_context,
+ kernel_data_type,
+ layer_index,
+ attention_scale,
+ attention_config.has_sinks,
+ )
+ .expect(
+ "Failed to create AttentionWrapper with Metal kernel",
+ ),
+ );
+
+ MixerExecutables::Attention {
+ qkv_projection,
+ qk_norm,
+ rope: rope_block,
+ attention,
+ out_projection,
+ }
+ },
+ MixerConfig::Mamba(mamba_config) => {
+ let mixer: Box<dyn EncodableWithState> =
+ Box::new(MambaMixerEncodable::new(
+ mtl_context,
+ layer_type.clone(),
+ mamba_config.clone(),
+ compilation_config.clone(),
+ layer_index,
+ model_dim,
+ num_heads,
+ head_dim,
+ num_groups,
+ decoder_layer_loader,
+ ));
+ MixerExecutables::StateSpace {
+ mixer,
+ }
+ },
+ };
let post_attention_norm: Option<Box<dyn EncodableWithState>> =
if let Some(norm_config) =
@@ -156,7 +220,7 @@ impl LayerExecutables {
ArrayId::Main,
ArrayId::Main,
&decoder_layer_loader
- .subtree("post_attention_norm")
+ .subtree("post_mixer_norm")
.unwrap(),
)
.expect("Failed to create RMS norm kernel"),
@@ -214,26 +278,11 @@ impl LayerExecutables {
None
};
- let attention: Box<dyn EncodableWithState> = Box::new(
- AttentionKernelEncodable::new(
- mtl_context,
- kernel_data_type,
- layer_index,
- attention_scale,
- layer_config.attention_config.has_sinks,
- )
- .expect("Failed to create AttentionWrapper with Metal kernel"),
- );
-
Self {
layer_index,
copy_main_to_shortcut,
pre_attention_norm,
- qkv_projection,
- qk_norm,
- rope,
- attention,
- out_projection,
+ mixer,
post_attention_norm,
main_shortcut_add_swap,
pre_mlp_norm,
@@ -275,18 +324,39 @@ impl EncodableWithState for LayerExecutables {
);
}
- self.qkv_projection.encode(state, command_buffer, parameters);
- if let Some(ref qk_norm) = self.qk_norm {
- qk_norm.encode(state, command_buffer, parameters);
- }
- self.rope.encode(state, command_buffer, parameters);
- self.attention.encode(state, command_buffer, parameters);
- self.out_projection.encode(state, command_buffer, parameters);
- if let Some(layer_traces) = layer_traces.clone() {
- state.copy_array(
- ArrayId::Main,
- layer_traces.borrow().attention.clone(),
- );
+ match &self.mixer {
+ MixerExecutables::Attention {
+ qkv_projection,
+ qk_norm,
+ rope,
+ attention,
+ out_projection,
+ } => {
+ qkv_projection.encode(state, command_buffer, parameters);
+ if let Some(norm) = qk_norm {
+ norm.encode(state, command_buffer, parameters);
+ }
+ rope.encode(state, command_buffer, parameters);
+ attention.encode(state, command_buffer, parameters);
+ out_projection.encode(state, command_buffer, parameters);
+ if let Some(layer_traces) = layer_traces.clone() {
+ state.copy_array(
+ ArrayId::Main,
+ layer_traces.borrow().attention.clone(),
+ );
+ }
+ },
+ MixerExecutables::StateSpace {
+ mixer,
+ } => {
+ mixer.encode(state, command_buffer, parameters);
+ if let Some(layer_traces) = layer_traces.clone() {
+ state.copy_array(
+ ArrayId::Main,
+ layer_traces.borrow().attention.clone(),
+ );
+ }
+ },
}
if let Some(post_attention_norm) = &self.post_attention_norm {
diff --git a/crates/uzu/src/backends/metal/forward_pass/buffers.rs b/crates/uzu/src/backends/metal/forward_pass/buffers.rs
index 2ed74ca5c..7561371fb 100644
--- a/crates/uzu/src/backends/metal/forward_pass/buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/buffers.rs
@@ -9,10 +9,6 @@ use crate::{
config::{DecoderConfig, MLPConfig},
};
-/// Holds one shared Metal buffer for every temporary tensor that can appear during a forward pass.
-/// Each buffer is large enough for the worst-case shape: `max_suffix_len` / `max_prefix_len`.
-///
-/// Per-iteration code merely *wraps* the buffer into a `MetalArray` with the runtime shape.
#[derive(Debug)]
pub struct ForwardPassBuffers {
// 1-D
@@ -30,6 +26,14 @@ pub struct ForwardPassBuffers {
pub attention_output: MTLBuffer,
pub mlp_fused_up: MTLBuffer,
pub mlp_hidden: MTLBuffer,
+ pub ssm_inproj: Option<MTLBuffer>,
+ pub ssm_packed: Option<MTLBuffer>,
+ pub ssm_conv_padded: Option<MTLBuffer>,
+ pub ssm_x: Option<MTLBuffer>,
+ pub ssm_b: Option<MTLBuffer>,
+ pub ssm_c: Option<MTLBuffer>,
+ pub ssm_dt: Option<MTLBuffer>,
+ pub ssm_z: Option<MTLBuffer>,
// 3-D
pub rotated_queries: MTLBuffer,
@@ -122,7 +126,30 @@ impl ForwardPassBuffers {
&model_shape.mlp_hidden_shape(max_suffix_len),
act_ty,
),
-
+ ssm_inproj: model_shape
+ .ssm_inproj_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_packed: model_shape
+ .ssm_packed_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_conv_padded: model_shape
+ .ssm_conv_padded_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_x: model_shape
+ .ssm_x_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_b: model_shape
+ .ssm_bc_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_c: model_shape
+ .ssm_bc_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_dt: model_shape
+ .ssm_dt_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
+ ssm_z: model_shape
+ .ssm_z_shape(max_suffix_len)
+ .map(|shape| alloc(&shape, act_ty)),
// 3-D
rotated_queries: alloc(
&model_shape.rotated_queries_shape(max_suffix_len),
diff --git a/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs b/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
new file mode 100644
index 000000000..b0a19e413
--- /dev/null
+++ b/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
@@ -0,0 +1,325 @@
+use std::{cell::RefCell, collections::HashMap};
+
+use metal::CommandBuffer as MTLCommandBuffer;
+
+use super::{
+ super::{MTLContext, MetalArray},
+ kv_cache_layer::{INVALID_POSITION, KVCacheLayer, KVCacheLayerState},
+ model_shape::ModelShape,
+ ssm_layer::SSMLayer,
+};
+use crate::{
+ DeviceContext, array::Array, backends::metal::kernel::KVCacheUpdate,
+ config::DecoderLayerType,
+};
+
+#[derive(Debug)]
+pub enum CacheLayer {
+ Transformer(KVCacheLayer),
+ StateSpace(SSMLayer),
+}
+
+impl CacheLayer {
+ pub fn as_transformer(&self) -> Option<&KVCacheLayer> {
+ match self {
+ CacheLayer::Transformer(layer) => Some(layer),
+ _ => None,
+ }
+ }
+
+ pub fn as_transformer_mut(&mut self) -> Option<&mut KVCacheLayer> {
+ match self {
+ CacheLayer::Transformer(layer) => Some(layer),
+ _ => None,
+ }
+ }
+
+ pub fn as_state_space(&self) -> Option<&SSMLayer> {
+ match self {
+ CacheLayer::StateSpace(layer) => Some(layer),
+ _ => None,
+ }
+ }
+
+ pub fn as_state_space_mut(&mut self) -> Option<&mut SSMLayer> {
+ match self {
+ CacheLayer::StateSpace(layer) => Some(layer),
+ _ => None,
+ }
+ }
+}
+
+pub struct CacheLayers {
+ max_suffix_length: usize,
+ max_prefix_length: usize,
+ pub data: Box<[CacheLayer]>,
+}
+
+impl CacheLayers {
+ pub fn new(
+ context: &MTLContext,
+ model_shape: &ModelShape,
+ max_prefix_length: usize,
+ max_suffix_length: usize,
+ ) -> Self {
+ let total_context_length = max_prefix_length + max_suffix_length;
+ let kv_shapes: Vec<[usize; 3]> = model_shape
+ .kv_cache_layer_shapes(max_prefix_length, max_suffix_length)
+ .collect();
+
+ let data: Box<[CacheLayer]> =
+ model_shape
+ .layer_types()
+ .iter()
+ .enumerate()
+ .map(|(layer_idx, layer_type)| match layer_type {
+ DecoderLayerType::Transformer => {
+ let shape = kv_shapes[layer_idx];
+ let window_length = model_shape
+ .sliding_window_length_per_layer[layer_idx]
+ .filter(|&window_size| {
+ window_size < total_context_length
+ });
+
+ let state = if let Some(w) = window_length {
+ KVCacheLayerState::Windowed {
+ ring_offset: 0,
+ ring_length: 0,
+ window_length: w,
+ }
+ } else {
+ KVCacheLayerState::Full {
+ prefix_len: 0,
+ }
+ };
+
+ CacheLayer::Transformer(KVCacheLayer {
+ state: state.clone(),
+ keys: RefCell::new(context.array(
+ &shape,
+ model_shape.kv_cache_data_type(),
+ )),
+ values: RefCell::new(context.array(
+ &shape,
+ model_shape.kv_cache_data_type(),
+ )),
+ prefix_token_positions: match &state {
+ KVCacheLayerState::Full {
+ ..
+ } => Vec::with_capacity(max_prefix_length),
+ KVCacheLayerState::Windowed {
+ window_length,
+ ..
+ } => (0..*window_length)
+ .map(|_| INVALID_POSITION)
+ .collect(),
+ },
+ max_suffix_length,
+ })
+ },
+ DecoderLayerType::StateSpace {
+ conv_dim,
+ kernel_size,
+ state_dim,
+ num_heads,
+ head_dim,
+ ..
+ } => {
+ let conv_shape =
+ [*conv_dim, kernel_size.saturating_sub(1)];
+ let ssm_shape = [*num_heads, *head_dim, *state_dim];
+ let dtype = model_shape.activation_data_type();
+
+ CacheLayer::StateSpace(SSMLayer {
+ conv_state: RefCell::new(
+ context.array(&conv_shape, dtype),
+ ),
+ ssm_state: RefCell::new(
+ context.array(&ssm_shape, dtype),
+ ),
+ })
+ },
+ })
+ .collect();
+
+ Self {
+ max_suffix_length,
+ max_prefix_length,
+ data,
+ }
+ }
+
+ pub fn clear(&mut self) {
+ for layer in self.data.iter_mut() {
+ match layer {
+ CacheLayer::Transformer(layer) => match &mut layer.state {
+ KVCacheLayerState::Full {
+ prefix_len,
+ } => {
+ *prefix_len = 0;
+ layer.prefix_token_positions.clear();
+ },
+ KVCacheLayerState::Windowed {
+ ring_offset,
+ ring_length,
+ ..
+ } => {
+ *ring_offset = 0;
+ *ring_length = 0;
+ layer.prefix_token_positions.fill(INVALID_POSITION);
+ },
+ },
+ CacheLayer::StateSpace(layer) => layer.zero(),
+ }
+ }
+ }
+
+ pub fn max_suffix_length(&self) -> usize {
+ self.max_suffix_length
+ }
+
+ pub fn max_prefix_length(&self) -> usize {
+ self.max_prefix_length
+ }
+
+ pub fn fill_attention_bias(
+ &self,
+ dst: &mut HashMap<Option<usize>, MetalArray>,
+ suffix_token_positions: &[usize],
+ suffix_length: usize,
+ context: &MTLContext,
+ external_bias_fn: Option<&dyn Fn(usize, usize) -> bool>,
+ ) {
+ for layer in self.data.iter() {
+ if let CacheLayer::Transformer(layer) = layer {
+ let key: Option<usize> = match &layer.state {
+ KVCacheLayerState::Full {
+ ..
+ } => None,
+ KVCacheLayerState::Windowed {
+ window_length,
+ ..
+ } => Some(*window_length),
+ };
+
+ if let Some(array) = dst.get_mut(&key) {
+ layer.fill_attention_bias(
+ array,
+ suffix_token_positions,
+ suffix_length,
+ context,
+ external_bias_fn,
+ );
+ }
+ }
+ }
+ }
+
+ pub fn update_after_acceptance(
+ &mut self,
+ accepted_suffix_indices: &[usize],
+ suffix_start: Option<usize>,
+ command_buffer: &MTLCommandBuffer,
+ kv_cache_update: &KVCacheUpdate,
+ ) {
+ for layer in self.data.iter_mut() {
+ if let Some(layer) = layer.as_transformer_mut() {
+ layer.update_after_acceptance(
+ accepted_suffix_indices,
+ suffix_start,
+ command_buffer,
+ kv_cache_update,
+ );
+ }
+ }
+ }
+
+ pub fn register_accepted_tokens(
+ &mut self,
+ token_positions: &[usize],
+ ) {
+ for layer in self.data.iter_mut() {
+ if let Some(layer) = layer.as_transformer_mut() {
+ layer.register_accepted_tokens(token_positions);
+ }
+ }
+ }
+
+ pub fn clone(
+ &self,
+ context: &MTLContext,
+ ) -> Self {
+ let mut max_prefix_capacity_across_layers = 0usize;
+ let data: Box<[CacheLayer]> = self
+ .data
+ .iter()
+ .map(|layer| match layer {
+ CacheLayer::Transformer(layer) => {
+ let shape = layer.keys.borrow().shape().to_vec();
+ let num_groups = shape[0];
+ let head_dim = shape[2];
+ let dtype = layer.keys.borrow().data_type();
+ let copy_rows = layer.prefix_segment_length();
+
+ let new_total_len = copy_rows + self.max_suffix_length;
+ if copy_rows > max_prefix_capacity_across_layers {
+ max_prefix_capacity_across_layers = copy_rows;
+ }
+
+ let new_shape = [num_groups, new_total_len, head_dim];
+ let mut new_keys = context.array(&new_shape, dtype);
+ let mut new_values = context.array(&new_shape, dtype);
+
+ if copy_rows > 0 {
+ {
+ let keys = layer.keys.borrow();
+ new_keys.copy_slice(&keys, 1, 0..copy_rows, 0);
+ }
+ {
+ let values = layer.values.borrow();
+ new_values.copy_slice(&values, 1, 0..copy_rows, 0);
+ }
+ }
+
+ CacheLayer::Transformer(KVCacheLayer {
+ state: layer.state.clone(),
+ keys: RefCell::new(new_keys),
+ values: RefCell::new(new_values),
+ prefix_token_positions: layer
+ .prefix_token_positions
+ .clone(),
+ max_suffix_length: layer.max_suffix_length,
+ })
+ },
+ CacheLayer::StateSpace(layer) => {
+ let conv_shape = layer.conv_state.borrow().shape().to_vec();
+ let conv_dtype = layer.conv_state.borrow().data_type();
+ let mut new_conv = context.array(&conv_shape, conv_dtype);
+ {
+ let conv_src = layer.conv_state.borrow();
+ new_conv.copy_from_array(&conv_src);
+ }
+
+ let ssm_shape = layer.ssm_state.borrow().shape().to_vec();
+ let ssm_dtype = layer.ssm_state.borrow().data_type();
+ let mut new_ssm = context.array(&ssm_shape, ssm_dtype);
+ {
+ let ssm_src = layer.ssm_state.borrow();
+ new_ssm.copy_from_array(&ssm_src);
+ }
+
+ CacheLayer::StateSpace(SSMLayer {
+ conv_state: RefCell::new(new_conv),
+ ssm_state: RefCell::new(new_ssm),
+ })
+ },
+ })
+ .collect();
+
+ Self {
+ max_suffix_length: self.max_suffix_length,
+ max_prefix_length: max_prefix_capacity_across_layers,
+ data,
+ }
+ }
+}
diff --git a/crates/uzu/src/backends/metal/forward_pass/kv_cache.rs b/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
similarity index 54%
rename from crates/uzu/src/backends/metal/forward_pass/kv_cache.rs
rename to crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
index c8c444e21..558d865b8 100644
--- a/crates/uzu/src/backends/metal/forward_pass/kv_cache.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
@@ -1,29 +1,26 @@
-use std::{cell::RefCell, collections::HashMap};
+use std::cell::RefCell;
use metal::CommandBuffer as MTLCommandBuffer;
-use super::{
- super::{MTLContext, MetalArray},
- model_shape::ModelShape,
-};
+use super::super::{MTLContext, MetalArray};
use crate::{
DeviceContext,
array::Array,
backends::metal::kernel::{KVCacheUpdate, kv_cache_update::KVLayerData},
};
-type ArrayCell = RefCell<MetalArray>;
+pub type ArrayCell = RefCell<MetalArray>;
#[derive(Clone, Debug)]
pub enum KVCacheLayerState {
Full {
- // Prefix length so far (number of tokens in the prefix)
+ /// Prefix length so far (number of tokens in the prefix)
prefix_len: usize,
},
Windowed {
- // Start of the ring buffer (oldest element index)
+ /// Start of the ring buffer (oldest element index)
ring_offset: usize,
- // Current logical length of the window (<= window_length)
+ /// Current logical length of the window (<= window_length)
ring_length: usize,
window_length: usize,
},
@@ -31,6 +28,7 @@ pub enum KVCacheLayerState {
pub const INVALID_POSITION: usize = i32::MAX as usize;
+#[derive(Debug)]
pub struct KVCacheLayer {
pub state: KVCacheLayerState,
/// [num_groups, max_prefix_length + max_suffix_length, head_dim]
@@ -295,214 +293,3 @@ impl KVCacheLayer {
}
}
}
-
-pub struct KVCache {
- max_suffix_length: usize,
- max_prefix_length: usize,
- pub data: Box<[KVCacheLayer]>,
-}
-
-impl KVCache {
- pub fn new(
- context: &MTLContext,
- model_shape: &ModelShape,
- max_prefix_length: usize,
- max_suffix_length: usize,
- ) -> Self {
- let total_context_length = max_prefix_length + max_suffix_length;
- let data: Box<[KVCacheLayer]> = model_shape
- .kv_cache_layer_shapes(max_prefix_length, max_suffix_length)
- .enumerate()
- .map(|(layer_idx, shape)| {
- let window_length = model_shape.sliding_window_length_per_layer
- [layer_idx]
- .filter(|&window_size| window_size < total_context_length);
-
- let state = if let Some(w) = window_length {
- KVCacheLayerState::Windowed {
- ring_offset: 0,
- ring_length: 0,
- window_length: w,
- }
- } else {
- KVCacheLayerState::Full {
- prefix_len: 0,
- }
- };
-
- KVCacheLayer {
- state: state.clone(),
- keys: RefCell::new(
- context.array(&shape, model_shape.kv_cache_data_type()),
- ),
- values: RefCell::new(
- context.array(&shape, model_shape.kv_cache_data_type()),
- ),
- prefix_token_positions: match &state {
- KVCacheLayerState::Full {
- ..
- } => Vec::with_capacity(max_prefix_length),
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => (0..*window_length)
- .map(|_| INVALID_POSITION)
- .collect(),
- },
- max_suffix_length: max_suffix_length,
- }
- })
- .collect();
-
- Self {
- max_suffix_length,
- max_prefix_length,
- data,
- }
- }
-
- pub fn clear(&mut self) {
- for layer in self.data.iter_mut() {
- match &mut layer.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- *prefix_len = 0;
- layer.prefix_token_positions.clear();
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- ..
- } => {
- *ring_offset = 0;
- *ring_length = 0;
- layer.prefix_token_positions.fill(INVALID_POSITION);
- },
- }
- }
- }
-
- pub fn max_suffix_length(&self) -> usize {
- self.max_suffix_length
- }
-
- pub fn max_prefix_length(&self) -> usize {
- self.max_prefix_length
- }
-
- pub fn fill_attention_bias(
- &self,
- dst: &mut HashMap<Option<usize>, MetalArray>,
- suffix_token_positions: &[usize],
- suffix_length: usize,
- context: &MTLContext,
- external_bias_fn: Option<&dyn Fn(usize, usize) -> bool>,
- ) {
- for layer in self.data.iter() {
- let key: Option<usize> = match &layer.state {
- KVCacheLayerState::Full {
- ..
- } => None,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => Some(*window_length),
- };
-
- if let Some(array) = dst.get_mut(&key) {
- layer.fill_attention_bias(
- array,
- suffix_token_positions,
- suffix_length,
- context,
- external_bias_fn,
- );
- }
- }
- }
-
- pub fn update_after_acceptance(
- &mut self,
- accepted_suffix_indices: &[usize],
- suffix_start: Option<usize>,
- command_buffer: &MTLCommandBuffer,
- kv_cache_update: &KVCacheUpdate,
- ) {
- for layer in self.data.iter_mut() {
- layer.update_after_acceptance(
- accepted_suffix_indices,
- suffix_start,
- command_buffer,
- kv_cache_update,
- );
- }
- }
-
- pub fn register_accepted_tokens(
- &mut self,
- token_positions: &[usize],
- ) {
- for layer in self.data.iter_mut() {
- layer.register_accepted_tokens(token_positions);
- }
- }
-
- pub fn clone(
- &self,
- context: &MTLContext,
- ) -> Self {
- let mut max_prefix_capacity_across_layers = 0usize;
- let data: Box<[KVCacheLayer]> = self
- .data
- .iter()
- .map(|layer| {
- let shape = layer.keys.borrow().shape().to_vec();
- let num_groups = shape[0];
- let head_dim = shape[2];
- let dtype = layer.keys.borrow().data_type();
-
- let copy_rows = layer.prefix_segment_length();
- let new_total_len = copy_rows + self.max_suffix_length;
- if copy_rows > max_prefix_capacity_across_layers {
- max_prefix_capacity_across_layers = copy_rows;
- }
-
- let new_shape = [num_groups, new_total_len, head_dim];
- let mut new_keys = context.array(&new_shape, dtype);
- let mut new_values = context.array(&new_shape, dtype);
-
- if copy_rows > 0 {
- new_keys.copy_slice(
- &layer.keys.borrow(),
- 1,
- 0..copy_rows,
- 0,
- );
- new_values.copy_slice(
- &layer.values.borrow(),
- 1,
- 0..copy_rows,
- 0,
- );
- }
-
- KVCacheLayer {
- state: layer.state.clone(),
- keys: RefCell::new(new_keys),
- values: RefCell::new(new_values),
- prefix_token_positions: layer
- .prefix_token_positions
- .clone(),
- max_suffix_length: layer.max_suffix_length,
- }
- })
- .collect();
-
- Self {
- max_suffix_length: self.max_suffix_length,
- max_prefix_length: max_prefix_capacity_across_layers,
- data,
- }
- }
-}
diff --git a/crates/uzu/src/backends/metal/forward_pass/mod.rs b/crates/uzu/src/backends/metal/forward_pass/mod.rs
index 854fcbc28..92ce766f3 100644
--- a/crates/uzu/src/backends/metal/forward_pass/mod.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/mod.rs
@@ -1,18 +1,22 @@
mod buffers;
+pub mod cache_layers;
pub mod encodable_with_state;
mod io_arrays;
-pub mod kv_cache;
+pub mod kv_cache_layer;
mod model_shape;
mod mpsgraph_block;
+pub mod ssm_layer;
mod state;
pub mod traces;
pub mod transformer_layer;
pub use buffers::ForwardPassBuffers;
+pub use cache_layers::{CacheLayer, CacheLayers};
pub use io_arrays::IOArrays;
-pub use kv_cache::{KVCache, KVCacheLayer, KVCacheLayerState};
+pub use kv_cache_layer::{INVALID_POSITION, KVCacheLayer, KVCacheLayerState};
pub use model_shape::ModelShape;
pub use mpsgraph_block::MPSGraphBlock;
+pub use ssm_layer::SSMLayer;
pub use state::{
ArrayId, ForwardPassState, HashMapId, RopeType, SharedBuffers,
};
diff --git a/crates/uzu/src/backends/metal/forward_pass/model_shape.rs b/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
index 60b26d349..52dd9e470 100644
--- a/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
@@ -1,4 +1,7 @@
-use crate::{DataType, config::DecoderConfig};
+use crate::{
+ DataType,
+ config::{DecoderConfig, DecoderLayerType},
+};
#[derive(Debug)]
pub struct ModelShape {
@@ -15,6 +18,13 @@ pub struct ModelShape {
head_dim: usize,
pub num_layers: usize,
pub sliding_window_length_per_layer: Box<[Option<usize>]>,
+ pub layer_types: Box<[DecoderLayerType]>,
+ max_mamba_heads: usize,
+ max_mamba_groups: usize,
+ max_mamba_head_dim: usize,
+ max_mamba_conv_dim: usize,
+ max_mamba_state_dim: usize,
+ max_mamba_kernel_size: usize,
}
impl ModelShape {
@@ -29,6 +39,46 @@ impl ModelShape {
},
};
let num_layers = decoder_config.num_layers;
+ let layer_types: Box<[DecoderLayerType]> = if let Some(layer_types) =
+ &decoder_config.layer_types
+ {
+ assert_eq!(
+ layer_types.len(),
+ num_layers,
+ "layer_types entry count ({}) must equal num_layers ({})",
+ layer_types.len(),
+ num_layers
+ );
+ layer_types.clone()
+ } else {
+ vec![DecoderLayerType::Transformer; num_layers].into_boxed_slice()
+ };
+ let mut max_mamba_heads = 0;
+ let mut max_mamba_groups = 0;
+ let mut max_mamba_head_dim = 0;
+ let mut max_mamba_conv_dim = 0;
+ let mut max_mamba_state_dim = 0;
+ let mut max_mamba_kernel_size = 0;
+ for layer in layer_types.iter() {
+ if let DecoderLayerType::StateSpace {
+ conv_dim,
+ kernel_size,
+ state_dim,
+ num_heads,
+ num_groups,
+ head_dim,
+ ..
+ } = layer
+ {
+ max_mamba_heads = max_mamba_heads.max(*num_heads);
+ max_mamba_groups = max_mamba_groups.max(*num_groups);
+ max_mamba_head_dim = max_mamba_head_dim.max(*head_dim);
+ max_mamba_conv_dim = max_mamba_conv_dim.max(*conv_dim);
+ max_mamba_state_dim = max_mamba_state_dim.max(*state_dim);
+ max_mamba_kernel_size =
+ max_mamba_kernel_size.max(*kernel_size as usize);
+ }
+ }
Self {
activation_type,
kv_cache_type: activation_type,
@@ -44,6 +94,13 @@ impl ModelShape {
.sliding_window_sizes
.clone()
.unwrap_or(vec![None; num_layers].into_boxed_slice()),
+ layer_types,
+ max_mamba_heads,
+ max_mamba_groups,
+ max_mamba_head_dim,
+ max_mamba_conv_dim,
+ max_mamba_state_dim,
+ max_mamba_kernel_size,
}
}
@@ -63,6 +120,21 @@ impl ModelShape {
self.head_dim
}
+ pub fn num_groups(&self) -> usize {
+ self.num_groups
+ }
+
+ pub fn layer_type(
+ &self,
+ layer_index: usize,
+ ) -> &DecoderLayerType {
+ &self.layer_types[layer_index]
+ }
+
+ pub fn layer_types(&self) -> &[DecoderLayerType] {
+ &self.layer_types
+ }
+
pub fn main_shape(
&self,
suffix_length: usize,
@@ -287,4 +359,118 @@ impl ModelShape {
// nan_gate_bits, nan_up_bits]
[8]
}
+
+ pub fn ssm_inproj_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 2]> {
+ self.max_mamba_inproj_dim_internal().map(|dim| [suffix_length, dim])
+ }
+
+ pub fn has_state_space_layers(&self) -> bool {
+ self.max_mamba_heads > 0
+ }
+
+ pub fn max_mamba_conv_dim(&self) -> Option<usize> {
+ if self.max_mamba_conv_dim == 0 {
+ None
+ } else {
+ Some(self.max_mamba_conv_dim)
+ }
+ }
+
+ pub fn max_mamba_state_dim(&self) -> Option<usize> {
+ if self.max_mamba_state_dim == 0 {
+ None
+ } else {
+ Some(self.max_mamba_state_dim)
+ }
+ }
+
+ pub fn max_mamba_kernel_size(&self) -> Option<usize> {
+ if self.max_mamba_kernel_size == 0 {
+ None
+ } else {
+ Some(self.max_mamba_kernel_size)
+ }
+ }
+
+ pub fn ssm_packed_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 2]> {
+ self.max_mamba_conv_dim().map(|dim| [suffix_length, dim])
+ }
+
+ pub fn ssm_conv_padded_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 2]> {
+ match (self.max_mamba_conv_dim(), self.max_mamba_kernel_size()) {
+ (Some(conv_dim), Some(kernel_size)) if kernel_size > 0 => {
+ Some([suffix_length + kernel_size - 1, conv_dim])
+ },
+ _ => None,
+ }
+ }
+
+ pub fn ssm_x_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 3]> {
+ if self.has_state_space_layers() {
+ Some([suffix_length, self.max_mamba_heads, self.max_mamba_head_dim])
+ } else {
+ None
+ }
+ }
+
+ pub fn ssm_z_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 3]> {
+ self.ssm_x_shape(suffix_length)
+ }
+
+ pub fn ssm_dt_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 2]> {
+ if self.has_state_space_layers() {
+ Some([suffix_length, self.max_mamba_heads])
+ } else {
+ None
+ }
+ }
+
+ pub fn ssm_bc_shape(
+ &self,
+ suffix_length: usize,
+ ) -> Option<[usize; 3]> {
+ if self.has_state_space_layers() {
+ self.max_mamba_state_dim().map(|state_dim| {
+ [suffix_length, self.max_mamba_groups, state_dim]
+ })
+ } else {
+ None
+ }
+ }
+
+ fn max_mamba_inproj_dim_internal(&self) -> Option<usize> {
+ self.layer_types
+ .iter()
+ .filter_map(|layer_type| match layer_type {
+ DecoderLayerType::StateSpace {
+ conv_dim,
+ num_heads,
+ head_dim,
+ ..
+ } => {
+ let inner_dim = num_heads * head_dim;
+ Some(conv_dim + inner_dim + num_heads)
+ },
+ _ => None,
+ })
+ .max()
+ }
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/ssm_layer.rs b/crates/uzu/src/backends/metal/forward_pass/ssm_layer.rs
new file mode 100644
index 000000000..1f633d314
--- /dev/null
+++ b/crates/uzu/src/backends/metal/forward_pass/ssm_layer.rs
@@ -0,0 +1,23 @@
+use bytemuck::fill_zeroes;
+
+use super::kv_cache_layer::ArrayCell;
+use crate::device::array::Array;
+
+#[derive(Debug)]
+pub struct SSMLayer {
+ pub conv_state: ArrayCell,
+ pub ssm_state: ArrayCell,
+}
+
+impl SSMLayer {
+ pub fn zero(&self) {
+ {
+ let mut conv = self.conv_state.borrow_mut();
+ fill_zeroes(conv.buffer_mut());
+ }
+ {
+ let mut ssm = self.ssm_state.borrow_mut();
+ fill_zeroes(ssm.buffer_mut());
+ }
+ }
+}
diff --git a/crates/uzu/src/backends/metal/forward_pass/state.rs b/crates/uzu/src/backends/metal/forward_pass/state.rs
index cf0b00503..454dea87f 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use super::{
super::{MTLContext, MetalArray},
buffers::ForwardPassBuffers,
- kv_cache::KVCache,
+ cache_layers::CacheLayers,
model_shape::ModelShape,
};
use crate::{
@@ -38,6 +38,16 @@ pub enum EmbeddingsBuffers {
/// [vocab_size]
scales: ArrayCell,
},
+ MLXSemiQuantizedUntied {
+ /// [vocab_size, model_dim]
+ input_weights: ArrayCell,
+ /// [vocab_size, model_dim]
+ packed_output_weights: ArrayCell,
+ /// [vocab_size, num_groups]
+ output_scales: ArrayCell,
+ /// [vocab_size, num_groups]
+ output_biases: ArrayCell,
+ },
}
impl EmbeddingsBuffers {
@@ -73,15 +83,92 @@ impl EmbeddingsBuffers {
EmbeddingConfig::QuantizedTied {
embedding_quantization_mode,
..
- } => Self::QuantizedTied {
- weights: RefCell::new(context.array_uninitialized(
- &model_shape.quantized_embeddings_weights_shape(),
- (*embedding_quantization_mode).into(),
- )),
- scales: RefCell::new(context.array_uninitialized(
- &model_shape.quantized_embeddings_scales_shape(),
- model_shape.activation_data_type(),
- )),
+ } => {
+ let [vocab_size, model_dim] =
+ model_shape.quantized_embeddings_weights_shape();
+ Self::QuantizedTied {
+ weights: RefCell::new(
+ context.array_uninitialized(
+ &[
+ vocab_size,
+ model_dim
+ / embedding_quantization_mode
+ .packing_divisor(),
+ ],
+ embedding_quantization_mode.storage_type(),
+ ),
+ ),
+ scales: RefCell::new(context.array_uninitialized(
+ &model_shape.quantized_embeddings_scales_shape(),
+ model_shape.activation_data_type(),
+ )),
+ }
+ },
+ EmbeddingConfig::MLXQuantizedTied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ let [vocab_size, model_dim] =
+ model_shape.quantized_embeddings_weights_shape();
+ let num_groups = model_dim / group_size;
+ Self::QuantizedTied {
+ weights: RefCell::new(
+ context.array_uninitialized(
+ &[
+ vocab_size,
+ model_dim
+ / embedding_quantization_mode
+ .packing_divisor(),
+ ],
+ embedding_quantization_mode.storage_type(),
+ ),
+ ),
+ scales: RefCell::new(context.array_uninitialized(
+ &[vocab_size, num_groups],
+ model_shape.activation_data_type(),
+ )),
+ }
+ },
+ EmbeddingConfig::MLXSemiQuantizedUntied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ let [vocab_size, model_dim] =
+ model_shape.quantized_embeddings_weights_shape();
+ let num_groups = model_dim / group_size;
+ Self::MLXSemiQuantizedUntied {
+ input_weights: RefCell::new(
+ context.array_uninitialized(
+ &model_shape.embeddings_input_shape(),
+ model_shape.activation_data_type(),
+ ),
+ ),
+ packed_output_weights: RefCell::new(
+ context.array_uninitialized(
+ &[
+ vocab_size,
+ model_dim
+ / embedding_quantization_mode
+ .packing_divisor(),
+ ],
+ embedding_quantization_mode.storage_type(),
+ ),
+ ),
+ output_scales: RefCell::new(
+ context.array_uninitialized(
+ &[vocab_size, num_groups],
+ model_shape.activation_data_type(),
+ ),
+ ),
+ output_biases: RefCell::new(
+ context.array_uninitialized(
+ &[vocab_size, num_groups],
+ model_shape.activation_data_type(),
+ ),
+ ),
+ }
},
}
}
@@ -122,6 +209,23 @@ impl EmbeddingsBuffers {
buffer.borrow_mut().copy_from_array(&view);
}
},
+ EmbeddingsBuffers::MLXSemiQuantizedUntied {
+ input_weights,
+ packed_output_weights,
+ output_scales,
+ output_biases,
+ } => {
+ let mapping = vec![
+ ("input_weights", input_weights),
+ ("output_weights", packed_output_weights),
+ ("output_scales", output_scales),
+ ("output_biases", output_biases),
+ ];
+ for (name, buffer) in mapping {
+ let view = embeddings_tree.leaf(name).unwrap();
+ buffer.borrow_mut().copy_from_array(&view);
+ }
+ },
}
}
}
@@ -161,7 +265,9 @@ impl RopeBuffers {
parameter_tree: &ParameterTree<Rc<MTLContext>>,
rope_name: String,
) {
- let rope_tree = parameter_tree.subtree(rope_name.as_str()).unwrap();
+ let Ok(rope_tree) = parameter_tree.subtree(rope_name.as_str()) else {
+ return;
+ };
let cosines_view = rope_tree.leaf("cosines").unwrap();
self.cosines.borrow_mut().copy_from_array(&cosines_view);
@@ -173,7 +279,7 @@ impl RopeBuffers {
pub struct SharedBuffers {
pub embeddings: EmbeddingsBuffers,
- pub global_rope: RopeBuffers,
+ pub global_rope: Option<RopeBuffers>,
pub local_rope: Option<RopeBuffers>,
pub moe_expert_weights: Option<Vec<MoeExpertWeights>>,
pub attention_sinks: Option<Vec<ArrayCell>>,
@@ -197,7 +303,11 @@ impl SharedBuffers {
model_shape,
);
- let global_rope = RopeBuffers::new(context, model_shape);
+ let global_rope = if decoder_config.global_rope_config.is_some() {
+ Some(RopeBuffers::new(context, model_shape))
+ } else {
+ None
+ };
let local_rope = if decoder_config.local_rope_config.is_some() {
Some(RopeBuffers::new(context, model_shape))
@@ -214,8 +324,10 @@ impl SharedBuffers {
None
};
- let attention_sinks =
- if decoder_config.layer_config.attention_config.has_sinks {
+ let attention_sinks = if let Some(attention_config) =
+ decoder_config.layer_config.attention_config()
+ {
+ if attention_config.has_sinks {
let num_heads = decoder_config.num_heads;
Some(
(0..decoder_config.num_layers)
@@ -229,7 +341,10 @@ impl SharedBuffers {
)
} else {
None
- };
+ }
+ } else {
+ None
+ };
Self {
embeddings,
@@ -245,8 +360,10 @@ impl SharedBuffers {
parameter_tree: &ParameterTree<Rc<MTLContext>>,
) {
self.embeddings.update_data(parameter_tree);
- self.global_rope
- .update_data(parameter_tree, String::from("global_rope"));
+ if let Some(global_rope) = &mut self.global_rope {
+ global_rope
+ .update_data(parameter_tree, String::from("global_rope"));
+ }
if let Some(local_rope) = &mut self.local_rope {
local_rope.update_data(parameter_tree, String::from("local_rope"));
}
@@ -256,7 +373,7 @@ impl SharedBuffers {
let layer_tree = parameter_tree
.subtree(&format!("layers.{}", layer_idx))
.unwrap();
- let attn_tree = layer_tree.subtree("attention").unwrap();
+ let attn_tree = layer_tree.subtree("mixer").unwrap();
let sinks_arr = attn_tree.leaf("sinks").unwrap();
let mut dst = sink_cell.borrow_mut();
let dst_slice = dst.as_slice_mut::<f32>().unwrap();
@@ -308,6 +425,22 @@ struct AuxBuffers {
mlp_fused_up: ArrayCell,
/// [suffix_length, hidden_dim]
mlp_hidden: ArrayCell,
+ /// [suffix_length, max_mamba_inproj_dim]
+ ssm_inproj: Option<ArrayCell>,
+ /// [suffix_length, max_conv_dim]
+ ssm_packed: Option<ArrayCell>,
+ /// [suffix_length + kernel_size - 1, max_conv_dim]
+ ssm_conv_padded: Option<ArrayCell>,
+ /// [suffix_length, num_heads, head_dim]
+ ssm_x: Option<ArrayCell>,
+ /// [suffix_length, num_groups, state_dim]
+ ssm_b: Option<ArrayCell>,
+ /// [suffix_length, num_groups, state_dim]
+ ssm_c: Option<ArrayCell>,
+ /// [suffix_length, num_heads]
+ ssm_dt: Option<ArrayCell>,
+ /// [suffix_length, num_heads, head_dim]
+ ssm_z: Option<ArrayCell>,
/// [num_heads, max_suffix_length, head_dim]
rotated_queries: ArrayCell,
/// [num_groups, max_suffix_length, head_dim]
@@ -381,6 +514,78 @@ impl AuxBuffers {
&model_shape.mlp_hidden_shape(suffix_length),
act_dtype,
)),
+ ssm_inproj: match (
+ scratch.ssm_inproj.as_ref(),
+ model_shape.ssm_inproj_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_packed: match (
+ scratch.ssm_packed.as_ref(),
+ model_shape.ssm_packed_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_conv_padded: match (
+ scratch.ssm_conv_padded.as_ref(),
+ model_shape.ssm_conv_padded_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_x: match (
+ scratch.ssm_x.as_ref(),
+ model_shape.ssm_x_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_b: match (
+ scratch.ssm_b.as_ref(),
+ model_shape.ssm_bc_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_c: match (
+ scratch.ssm_c.as_ref(),
+ model_shape.ssm_bc_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_dt: match (
+ scratch.ssm_dt.as_ref(),
+ model_shape.ssm_dt_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
+ ssm_z: match (
+ scratch.ssm_z.as_ref(),
+ model_shape.ssm_z_shape(suffix_length),
+ ) {
+ (Some(buf), Some(shape)) => Some(RefCell::new(
+ MetalArray::new(buf.clone(), &shape, act_dtype),
+ )),
+ _ => None,
+ },
rotated_queries: RefCell::new(MetalArray::new(
scratch.rotated_queries.clone(),
&model_shape.rotated_queries_shape(suffix_length),
@@ -696,10 +901,6 @@ impl AuxBuffers {
}
}
}
-
- fn suffix_length(&self) -> usize {
- self.suffix_length
- }
}
pub struct ForwardPassState {
@@ -714,7 +915,7 @@ pub struct ForwardPassState {
attention_bias: HashMap<Option<usize>, ArrayCell>,
/// [suffix_length, vocabulary_size]
logits: ArrayCell,
- pub kv_cache: Rc<RefCell<KVCache>>,
+ pub cache_layers: Rc<RefCell<CacheLayers>>,
pub shared_buffers: Rc<RefCell<SharedBuffers>>,
aux_buffers: AuxBuffers,
/// [suffix_length] - u32 sampling output buffer
@@ -722,6 +923,8 @@ pub struct ForwardPassState {
/// Current sampling configuration for this forward pass
pub sampling_method: Option<SamplingMethod>,
pub traces: Option<Rc<RefCell<DecoderActivationTrace>>>,
+ active_suffix_length: usize,
+ is_prefilling: bool,
}
impl ForwardPassState {
@@ -730,10 +933,12 @@ impl ForwardPassState {
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
scratch: &ForwardPassBuffers,
- kv_cache: Rc<RefCell<KVCache>>,
+ cache_layers: Rc<RefCell<CacheLayers>>,
shared_buffers: Rc<RefCell<SharedBuffers>>,
token_ids: &[u64],
token_positions: &[usize],
+ active_suffix_length: usize,
+ is_prefilling: bool,
token_seeds: &[u64],
trace: bool,
external_bias_fn: Option<&dyn Fn(usize, usize) -> bool>,
@@ -747,11 +952,15 @@ impl ForwardPassState {
token_positions.len()
);
assert!(
- suffix_length <= kv_cache.borrow().max_suffix_length(),
+ suffix_length <= cache_layers.borrow().max_suffix_length(),
"KV cache size can only accomodate a suffix of length up to {}, but tried to use a suffix of length {}",
- kv_cache.borrow().max_suffix_length(),
+ cache_layers.borrow().max_suffix_length(),
suffix_length
);
+ assert!(
+ active_suffix_length <= suffix_length,
+ "Active suffix length ({active_suffix_length}) must be <= suffix length ({suffix_length})"
+ );
let aux_buffers = AuxBuffers::new(
scratch,
decoder_config,
@@ -815,7 +1024,7 @@ impl ForwardPassState {
.iter()
.map(|(window_size, buffer)| {
let prefix_length = window_size
- .unwrap_or(kv_cache.borrow().max_prefix_length());
+ .unwrap_or(cache_layers.borrow().max_prefix_length());
let attention_bias_shape =
[suffix_length, suffix_length + prefix_length];
@@ -830,7 +1039,7 @@ impl ForwardPassState {
})
.collect();
- kv_cache.borrow().fill_attention_bias(
+ cache_layers.borrow().fill_attention_bias(
&mut attention_bias_map,
token_positions,
suffix_length,
@@ -880,12 +1089,14 @@ impl ForwardPassState {
token_seeds: token_seeds_refcell,
attention_bias,
logits,
- kv_cache,
+ cache_layers,
shared_buffers,
aux_buffers,
sampling_output: Some(sampling_output),
sampling_method: None,
traces,
+ active_suffix_length,
+ is_prefilling,
}
}
@@ -906,11 +1117,99 @@ impl ForwardPassState {
},
ArrayId::MlpFusedUp => self.aux_buffers.mlp_fused_up.clone(),
ArrayId::MlpHidden => self.aux_buffers.mlp_hidden.clone(),
+ ArrayId::SsmInProj => self
+ .aux_buffers
+ .ssm_inproj
+ .as_ref()
+ .expect("SSM in-projection buffer requested but not initialized")
+ .clone(),
ArrayId::Keys(layer_index) => {
- self.kv_cache.borrow().data[layer_index].keys.clone()
+ let cache = self.cache_layers.borrow();
+ match cache.data[layer_index].as_transformer() {
+ Some(layer) => layer.keys.clone(),
+ None => panic!(
+ "Requested transformer keys for non-transformer layer {}",
+ layer_index
+ ),
+ }
},
ArrayId::Values(layer_index) => {
- self.kv_cache.borrow().data[layer_index].values.clone()
+ let cache = self.cache_layers.borrow();
+ match cache.data[layer_index].as_transformer() {
+ Some(layer) => layer.values.clone(),
+ None => panic!(
+ "Requested transformer values for non-transformer layer {}",
+ layer_index
+ ),
+ }
+ },
+ ArrayId::SsmConvState(layer_index) => {
+ let cache = self.cache_layers.borrow();
+ match cache.data[layer_index].as_state_space() {
+ Some(layer) => layer.conv_state.clone(),
+ None => panic!(
+ "Requested SSM conv state for transformer layer {}",
+ layer_index
+ ),
+ }
+ },
+ ArrayId::SsmState(layer_index) => {
+ let cache = self.cache_layers.borrow();
+ match cache.data[layer_index].as_state_space() {
+ Some(layer) => layer.ssm_state.clone(),
+ None => panic!(
+ "Requested SSM state for transformer layer {}",
+ layer_index
+ ),
+ }
+ },
+ ArrayId::SsmPacked(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_packed
+ .as_ref()
+ .expect("SSM packed buffer not initialized")
+ .clone()
+ },
+ ArrayId::SsmX(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_x
+ .as_ref()
+ .expect("SSM x buffer not initialized")
+ .clone()
+ },
+ ArrayId::SsmB(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_b
+ .as_ref()
+ .expect("SSM b buffer not initialized")
+ .clone()
+ },
+ ArrayId::SsmC(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_c
+ .as_ref()
+ .expect("SSM c buffer not initialized")
+ .clone()
+ },
+ ArrayId::SsmDt(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_dt
+ .as_ref()
+ .expect("SSM dt buffer not initialized")
+ .clone()
+ },
+ ArrayId::SsmZ(layer_index) => {
+ let _ = layer_index;
+ self.aux_buffers
+ .ssm_z
+ .as_ref()
+ .expect("SSM z buffer not initialized")
+ .clone()
},
ArrayId::RotatedQueries => self.aux_buffers.rotated_queries.clone(),
ArrayId::RotatedKeys => self.aux_buffers.rotated_keys.clone(),
@@ -933,6 +1232,10 @@ impl ForwardPassState {
weights,
..
} => weights.clone(),
+ EmbeddingsBuffers::MLXSemiQuantizedUntied {
+ input_weights,
+ ..
+ } => input_weights.clone(),
}
},
ArrayId::EmbeddingsOutputWeights => {
@@ -948,6 +1251,10 @@ impl ForwardPassState {
weights,
..
} => weights.clone(),
+ EmbeddingsBuffers::MLXSemiQuantizedUntied {
+ packed_output_weights,
+ ..
+ } => packed_output_weights.clone(),
}
},
ArrayId::EmbeddingsScales => {
@@ -956,12 +1263,24 @@ impl ForwardPassState {
scales,
..
} => scales.clone(),
- _ => panic!("Expected EmbeddingsBuffers::QuantizedTied"),
+ EmbeddingsBuffers::MLXSemiQuantizedUntied {
+ output_scales,
+ ..
+ } => output_scales.clone(),
+ _ => panic!(
+ "Expected EmbeddingsBuffers::QuantizedTied or MLXSemiQuantizedUntied"
+ ),
}
},
ArrayId::RopeCosines(rope_type) => match rope_type {
RopeType::Global => {
- self.shared_buffers.borrow().global_rope.cosines.clone()
+ let shared_buffers = self.shared_buffers.borrow();
+ shared_buffers
+ .global_rope
+ .as_ref()
+ .expect("Global rope requested but not initialized")
+ .cosines
+ .clone()
},
RopeType::Local => self
.shared_buffers
@@ -974,7 +1293,13 @@ impl ForwardPassState {
},
ArrayId::RopeSines(rope_type) => match rope_type {
RopeType::Global => {
- self.shared_buffers.borrow().global_rope.sines.clone()
+ let shared_buffers = self.shared_buffers.borrow();
+ shared_buffers
+ .global_rope
+ .as_ref()
+ .expect("Global rope requested but not initialized")
+ .sines
+ .clone()
},
RopeType::Local => self
.shared_buffers
@@ -1049,12 +1374,24 @@ impl ForwardPassState {
}
pub fn aux_buffers_suffix_length(&self) -> usize {
- self.aux_buffers.suffix_length()
+ self.aux_buffers.suffix_length
+ }
+
+ pub fn active_suffix_length(&self) -> usize {
+ self.active_suffix_length
+ }
+
+ pub fn is_prefilling(&self) -> bool {
+ self.is_prefilling
}
pub fn mtl_context(&self) -> &Rc<MTLContext> {
&self.context
}
+
+ pub fn conv_padded_buffer(&self) -> Option<ArrayCell> {
+ self.aux_buffers.ssm_conv_padded.as_ref().map(|buf| buf.clone())
+ }
}
impl Drop for ForwardPassState {
@@ -1104,9 +1441,18 @@ pub enum ArrayId {
AttentionOutput,
MlpFusedUp,
MlpHidden,
+ SsmInProj,
Keys(usize),
Values(usize),
+ SsmConvState(usize),
+ SsmState(usize),
+ SsmPacked(usize),
+ SsmX(usize),
+ SsmB(usize),
+ SsmC(usize),
+ SsmDt(usize),
+ SsmZ(usize),
RotatedQueries,
RotatedKeys,
diff --git a/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs b/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
index fd4f3f22a..fec5b39dd 100644
--- a/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
@@ -24,6 +24,10 @@ use crate::{
},
kernel::{
MoeBlockEncodable, QuantizedLinearKernelBlock,
+ embedding::{
+ QuantizedEmbeddingLookupKernelBlock,
+ QuantizedEmbeddingReadoutKernelBlock,
+ },
mlp::MlpGateActMulEncodable,
},
},
@@ -64,6 +68,19 @@ pub fn linear_block<const N: usize>(
)
.unwrap();
}
+ if let LinearConfig::MLXQuantized(quant_config) = config {
+ let out_sum: usize = output_dims.iter().sum();
+ return quantized_linear_block_custom(
+ quant_config,
+ input_dim,
+ out_sum,
+ context,
+ parameter_tree,
+ input_array_id,
+ output_array_id,
+ )
+ .unwrap();
+ }
autoreleasepool(|_| {
let graph = Graph::new();
@@ -121,7 +138,7 @@ pub fn quantized_linear_block_custom(
Box<dyn super::encodable_with_state::EncodableWithState>,
crate::backends::metal::MTLError,
> {
- let block = crate::backends::metal::kernel::linear::QuantizedLinearKernelBlock::new(
+ let block = QuantizedLinearKernelBlock::new(
context,
config,
input_dim,
@@ -142,7 +159,8 @@ pub fn mlp_block(
compilation_descriptor: &CompilationDescriptor,
) -> Box<dyn super::encodable_with_state::EncodableWithState> {
if let crate::config::MLPConfig::Dense(dense) = config {
- if let crate::config::LinearConfig::Quantized(ref quant_config) =
+ if let crate::config::LinearConfig::Quantized(ref quant_config)
+ | crate::config::LinearConfig::MLXQuantized(ref quant_config) =
dense.linear_config
{
// Quantized MLP path: up (2H) -> act+mul -> down
@@ -263,6 +281,7 @@ pub fn embed_block(
config: &DecoderConfig,
context: &MTLContext,
compilation_descriptor: &CompilationDescriptor,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
) -> Box<dyn super::encodable_with_state::EncodableWithState> {
let graph = Graph::new();
@@ -362,14 +381,59 @@ pub fn embed_block(
Box::new(block)
},
- EmbeddingConfig::QuantizedTied {
- embedding_quantization_mode,
+ EmbeddingConfig::MLXSemiQuantizedUntied {
+ activation_precision,
..
} => {
let weights_shape =
[config.vocab_size as isize, config.model_dim as isize];
- let weights_data_type: DataType =
- embedding_quantization_mode.into();
+ let weights_data_type: DataType = activation_precision.into();
+ let weights_shaped_type =
+ shaped_type(&weights_shape, weights_data_type);
+ let weights_placeholder =
+ placeholder(&graph, &weights_shape, weights_data_type);
+
+ let output = embeddings_embed_subgraph(
+ &graph,
+ &config.embedding_config,
+ &input_placeholder,
+ &weights_placeholder,
+ )
+ .unwrap();
+
+ let feeds = HashMap::from([
+ (&*input_placeholder, &*input_shaped_type),
+ (&*weights_placeholder, &*weights_shaped_type),
+ ]);
+
+ let executable = graph.compile(
+ &MPSDevice::with_device(&context.device),
+ &feeds,
+ &[&output],
+ None,
+ Some(&compilation_descriptor),
+ );
+
+ let block = MPSGraphBlock::new(
+ executable,
+ make_execution_descriptor(),
+ IOArrays::new(
+ vec![ArrayId::TokenIds, ArrayId::EmbeddingsInputWeights]
+ .into_boxed_slice(),
+ vec![ArrayId::Main].into_boxed_slice(),
+ ),
+ );
+
+ Box::new(block)
+ },
+ EmbeddingConfig::QuantizedTied {
+ embedding_quantization_mode: _,
+ ..
+ } => {
+ // Packed U8 weights with shape [vocab_size, model_dim / 2]
+ let weights_shape =
+ [config.vocab_size as isize, (config.model_dim / 2) as isize];
+ let weights_data_type = DataType::U8;
let weights_shaped_type =
shaped_type(&weights_shape, weights_data_type);
let weights_placeholder =
@@ -426,6 +490,33 @@ pub fn embed_block(
),
);
+ Box::new(block)
+ },
+ EmbeddingConfig::MLXQuantizedTied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ // Use Metal kernel for MLX quantized embeddings
+ let data_type: DataType =
+ config.output_norm_config.scale_precision.into();
+
+ // Get the embeddings subtree
+ let embeddings_tree = parameter_tree
+ .subtree("embedding")
+ .expect("Failed to get embedding subtree");
+
+ let block = QuantizedEmbeddingLookupKernelBlock::new(
+ context,
+ data_type,
+ config.vocab_size,
+ config.model_dim,
+ group_size,
+ embedding_quantization_mode,
+ &embeddings_tree,
+ )
+ .expect("Failed to create quantized embedding lookup kernel");
+
Box::new(block)
},
}
@@ -435,6 +526,7 @@ pub fn readout_block(
config: &DecoderConfig,
context: &MTLContext,
compilation_descriptor: &CompilationDescriptor,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
) -> Box<dyn super::encodable_with_state::EncodableWithState> {
let graph = Graph::new();
@@ -537,14 +629,38 @@ pub fn readout_block(
Box::new(block)
},
- EmbeddingConfig::QuantizedTied {
+ EmbeddingConfig::MLXSemiQuantizedUntied {
+ group_size,
+ activation_precision,
embedding_quantization_mode,
..
} => {
+ let data_type: DataType = activation_precision.into();
+ let embeddings_tree = parameter_tree
+ .subtree("embedding")
+ .expect("Failed to get embedding subtree");
+
+ let block = QuantizedEmbeddingReadoutKernelBlock::new(
+ context,
+ data_type,
+ config.vocab_size,
+ config.model_dim,
+ group_size,
+ embedding_quantization_mode,
+ &embeddings_tree,
+ )
+ .expect("Failed to create quantized embedding readout kernel");
+
+ Box::new(block)
+ },
+ EmbeddingConfig::QuantizedTied {
+ embedding_quantization_mode: _,
+ ..
+ } => {
+ // Packed U8 weights with shape [vocab_size, model_dim / 2]
let weights_shape =
- [config.vocab_size as isize, config.model_dim as isize];
- let weights_data_type: DataType =
- embedding_quantization_mode.into();
+ [config.vocab_size as isize, (config.model_dim / 2) as isize];
+ let weights_data_type = DataType::U8;
let weights_shaped_type =
shaped_type(&weights_shape, weights_data_type);
let weights_placeholder =
@@ -600,6 +716,33 @@ pub fn readout_block(
),
);
+ Box::new(block)
+ },
+ EmbeddingConfig::MLXQuantizedTied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ // Use Metal kernel for MLX quantized readout
+ let data_type: DataType =
+ config.output_norm_config.scale_precision.into();
+
+ // Get the embeddings subtree
+ let embeddings_tree = parameter_tree
+ .subtree("embedding")
+ .expect("Failed to get embedding subtree");
+
+ let block = QuantizedEmbeddingReadoutKernelBlock::new(
+ context,
+ data_type,
+ config.vocab_size,
+ config.model_dim,
+ group_size,
+ embedding_quantization_mode,
+ &embeddings_tree,
+ )
+ .expect("Failed to create quantized embedding readout kernel");
+
Box::new(block)
},
}
diff --git a/crates/uzu/src/backends/metal/graph/common.rs b/crates/uzu/src/backends/metal/graph/common.rs
index a7b2978d3..078c10c68 100644
--- a/crates/uzu/src/backends/metal/graph/common.rs
+++ b/crates/uzu/src/backends/metal/graph/common.rs
@@ -50,13 +50,18 @@ pub fn activation(
data_type: DataType,
) -> Retained<Tensor> {
match config {
- Activation::SILU {
+ Activation::SiLU {
..
} => {
let sigmoid_result = graph.sigmoid(input, Some("sigmoid"));
graph.multiplication(input, &sigmoid_result, Some("silu_output"))
},
- Activation::GELU => gelu(graph, input, data_type, true),
+ Activation::Gelu => gelu(graph, input, data_type, true),
+ Activation::Identity => graph.addition(
+ input,
+ &graph.constant_with_scalar(0.0_f64, None, data_type.into()),
+ Some("identity_output"),
+ ),
}
}
diff --git a/crates/uzu/src/backends/metal/graph/linear.rs b/crates/uzu/src/backends/metal/graph/linear.rs
index e12dff387..1422d5b49 100644
--- a/crates/uzu/src/backends/metal/graph/linear.rs
+++ b/crates/uzu/src/backends/metal/graph/linear.rs
@@ -6,9 +6,7 @@ use objc2::rc::Retained;
use super::{super::MTLContext, GraphConstructionError, load_constant};
use crate::{
DataType,
- config::{
- ConfigDataType, LinearConfig, QuantizationConfig, QuantizationMode,
- },
+ config::{ConfigDataType, LinearConfig, QuantizationConfig},
parameters::ParameterTree,
};
@@ -36,14 +34,6 @@ fn quantized_weights_subgraph<const N: usize>(
output_dims: [usize; N],
parameter_tree: &ParameterTree<Rc<MTLContext>>,
) -> Result<Retained<Tensor>, GraphConstructionError> {
- if config.weight_quantization_mode != QuantizationMode::UInt4 {
- return Err(GraphConstructionError::IncompatibleDataTypes {
- node_path: parameter_tree.path_prefix().map(str::to_string),
- node_name: "weights".to_string(),
- expected: DataType::U4,
- actual: DataType::U8,
- });
- }
let output_dim_sum: usize = output_dims.iter().sum();
let weights = load_constant(
@@ -51,7 +41,7 @@ fn quantized_weights_subgraph<const N: usize>(
parameter_tree,
"weights",
&[input_dim, output_dim_sum],
- DataType::U4,
+ config.weight_quantization_mode.into(),
)?;
let scales = load_constant(
@@ -67,7 +57,7 @@ fn quantized_weights_subgraph<const N: usize>(
parameter_tree,
"zero_points",
&[input_dim, output_dim_sum / config.group_size],
- DataType::U4,
+ config.weight_quantization_mode.into(),
)?;
let result = graph.dequantize(
@@ -82,6 +72,51 @@ fn quantized_weights_subgraph<const N: usize>(
Ok(result)
}
+fn mlx_quantized_weights_subgraph<const N: usize>(
+ graph: &Graph,
+ config: &QuantizationConfig,
+ input_dim: usize,
+ output_dims: [usize; N],
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+) -> Result<Retained<Tensor>, GraphConstructionError> {
+ let output_dim_sum: usize = output_dims.iter().sum();
+
+ let weights = load_constant(
+ graph,
+ parameter_tree,
+ "weights",
+ &[input_dim, output_dim_sum],
+ config.weight_quantization_mode.into(),
+ )?;
+
+ let scales = load_constant(
+ graph,
+ parameter_tree,
+ "scales",
+ &[input_dim, output_dim_sum / config.group_size],
+ config.activation_precision.into(),
+ )?;
+
+ let deq_biases = load_constant(
+ graph,
+ parameter_tree,
+ "deq_biases",
+ &[input_dim, output_dim_sum / config.group_size],
+ config.activation_precision.into(),
+ )?;
+
+ let result = graph.dequantize(
+ &weights,
+ DequantizationArguments::ScaleTensorZeroPointTensorDataType {
+ scale_tensor: &scales,
+ zero_point_tensor: &deq_biases,
+ data_type: scales.data_type(),
+ },
+ None,
+ );
+ Ok(result)
+}
+
fn biases_subgraph<const N: usize>(
graph: &Graph,
precision: DataType,
@@ -175,6 +210,24 @@ fn quantized_matmul_subgraph<const N: usize>(
Ok(graph.matrix_multiplication(input, &weights, None))
}
+fn mlx_quantized_matmul_subgraph<const N: usize>(
+ graph: &Graph,
+ config: &QuantizationConfig,
+ input_dim: usize,
+ output_dims: [usize; N],
+ input: &Tensor,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+) -> Result<Retained<Tensor>, GraphConstructionError> {
+ let weights = mlx_quantized_weights_subgraph::<N>(
+ graph,
+ config,
+ input_dim,
+ output_dims,
+ parameter_tree,
+ )?;
+ Ok(graph.matrix_multiplication(input, &weights, None))
+}
+
fn lora_subgraph<const N: usize>(
graph: &Graph,
precision: DataType,
@@ -306,6 +359,16 @@ pub fn linear_subgraph<const N: usize>(
parameter_tree,
)?
},
+ LinearConfig::MLXQuantized(quantization_config) => {
+ mlx_quantized_matmul_subgraph(
+ graph,
+ quantization_config,
+ input_dim,
+ output_dims,
+ input,
+ parameter_tree,
+ )?
+ },
LinearConfig::QLoRA {
quantization: quantization_config,
lora_rank,
diff --git a/crates/uzu/src/backends/metal/kernel/attention/mod.rs b/crates/uzu/src/backends/metal/kernel/attention/mod.rs
index 309d6165e..43faaf496 100644
--- a/crates/uzu/src/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/attention/mod.rs
@@ -615,15 +615,20 @@ impl EncodableWithState for AttentionKernelEncodable {
)
};
- let segment_prefix_length = state.kv_cache.borrow().data
- [self.layer_index]
- .projected_segment_prefix_length(
- parameters.projection_step.unwrap_or(0),
- );
+ let (segment_prefix_length, window_length) = {
+ let cache = state.cache_layers.borrow();
+ let layer = cache.data[self.layer_index]
+ .as_transformer()
+ .expect("Attention kernel expects transformer layer state");
+ (
+ layer.projected_segment_prefix_length(
+ parameters.projection_step.unwrap_or(0),
+ ),
+ layer.window_length(),
+ )
+ };
let sequence_length = segment_prefix_length + suffix_length;
- let window_length =
- state.kv_cache.borrow().data[self.layer_index].window_length();
let gqa_factor = num_heads / num_groups;
let scale =
diff --git a/crates/uzu/src/backends/metal/kernel/embedding/mod.rs b/crates/uzu/src/backends/metal/kernel/embedding/mod.rs
new file mode 100644
index 000000000..0c8d5b693
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/embedding/mod.rs
@@ -0,0 +1,535 @@
+use std::{mem::size_of, rc::Rc};
+
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+use mpsgraph::CommandBuffer;
+
+use super::super::{
+ MTLContext,
+ forward_pass::{
+ ArrayId, ForwardPassState,
+ encodable_with_state::{EncodableWithState, EncodingParameters},
+ },
+};
+use crate::{
+ Array, DataType, backends::metal::MTLError, config::QuantizationMode,
+ parameters::ParameterTree,
+};
+
+#[derive(Debug, thiserror::Error)]
+pub enum QuantizedEmbeddingError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+ #[error("Unsupported data type: {0:?}")]
+ UnsupportedDataType(DataType),
+}
+
+pub struct QuantizedEmbeddingLookupKernel {
+ pipeline: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct QuantizedEmbeddingLookupArguments<'a> {
+ pub token_ids_buffer: &'a MTLBuffer, // [batch_size] as U64
+ pub weights_buffer: &'a MTLBuffer, // [vocab_size, model_dim/packing_divisor] as U8/I8
+ pub scales_buffer: &'a MTLBuffer, // [vocab_size, num_groups]
+ pub biases_buffer: &'a MTLBuffer, // [vocab_size, num_groups]
+ pub output_buffer: &'a MTLBuffer, // [batch_size, model_dim]
+ pub batch_size: u32,
+ pub vocab_size: u32,
+ pub model_dim: u32,
+ pub group_size: u32,
+}
+
+impl QuantizedEmbeddingLookupKernel {
+ pub fn new(
+ mtl_context: &MTLContext,
+ data_type: DataType,
+ mode: QuantizationMode,
+ ) -> Result<Self, QuantizedEmbeddingError> {
+ let dtype_suffix = match data_type {
+ DataType::F32 => "f32",
+ DataType::F16 => "f16",
+ DataType::BF16 => "bf16",
+ other => {
+ return Err(QuantizedEmbeddingError::UnsupportedDataType(
+ other,
+ ));
+ },
+ };
+ let mode_suffix = match mode {
+ QuantizationMode::UInt4 => "uint4",
+ QuantizationMode::Int8 => "int8",
+ QuantizationMode::UInt8 => "uint8",
+ };
+ let kernel_name = format!(
+ "quantized_embedding_lookup_{}_{}",
+ dtype_suffix, mode_suffix
+ );
+
+ let (pipeline, _) = mtl_context
+ .compute_pipeline_state_with_reflection(&kernel_name, None)
+ .map_err(QuantizedEmbeddingError::MetalError)?;
+
+ Ok(Self {
+ pipeline,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ encoder: &ComputeCommandEncoderRef,
+ args: QuantizedEmbeddingLookupArguments,
+ ) -> Result<(), QuantizedEmbeddingError> {
+ encoder.set_compute_pipeline_state(&self.pipeline);
+
+ // Set buffers
+ encoder.set_buffer(0, Some(args.token_ids_buffer), 0);
+ encoder.set_buffer(1, Some(args.weights_buffer), 0);
+ encoder.set_buffer(2, Some(args.scales_buffer), 0);
+ encoder.set_buffer(3, Some(args.biases_buffer), 0);
+ encoder.set_buffer(4, Some(args.output_buffer), 0);
+
+ // Set constants
+ encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &args.batch_size as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &args.vocab_size as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &args.model_dim as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 8,
+ size_of::<u32>() as u64,
+ &args.group_size as *const u32 as *const _,
+ );
+
+ // Dispatch one thread per output element
+ let total_threads = (args.batch_size * args.model_dim) as u64;
+ let threads_per_threadgroup = 256u64;
+ let threadgroups = (total_threads + threads_per_threadgroup - 1)
+ / threads_per_threadgroup;
+
+ encoder.dispatch_thread_groups(
+ MTLSize::new(threadgroups, 1, 1),
+ MTLSize::new(threads_per_threadgroup, 1, 1),
+ );
+
+ Ok(())
+ }
+}
+
+pub struct QuantizedEmbeddingLookupKernelBlock {
+ kernel: QuantizedEmbeddingLookupKernel,
+ weights_buffer: MTLBuffer,
+ scales_buffer: MTLBuffer,
+ biases_buffer: MTLBuffer,
+ vocab_size: u32,
+ model_dim: u32,
+ group_size: u32,
+}
+
+impl QuantizedEmbeddingLookupKernelBlock {
+ pub fn new(
+ mtl_context: &MTLContext,
+ data_type: DataType,
+ vocab_size: usize,
+ model_dim: usize,
+ group_size: usize,
+ mode: QuantizationMode,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+ ) -> Result<Self, QuantizedEmbeddingError> {
+ let packing_divisor = mode.packing_divisor();
+
+ let kernel =
+ QuantizedEmbeddingLookupKernel::new(mtl_context, data_type, mode)?;
+
+ // Load weights [vocab_size, model_dim/packing_divisor] as storage_type
+ let mut weights = match parameter_tree.leaf("weights") {
+ Ok(weights) => weights,
+ Err(_) => parameter_tree.leaf("output_weights").map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load weights: {:?}",
+ e
+ )))
+ })?,
+ };
+
+ if weights.data_type() != mode.storage_type() {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Expected packed weights of type {:?}, got {:?}",
+ mode.storage_type(),
+ weights.data_type()
+ )),
+ ));
+ }
+
+ // Load scales [vocab_size, num_groups]
+ let mut scales = match parameter_tree.leaf("scales") {
+ Ok(scales) => scales,
+ Err(_) => parameter_tree.leaf("output_scales").map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load scales: {:?}",
+ e
+ )))
+ })?,
+ };
+
+ // Validate shapes and types
+ let num_groups = (model_dim + group_size - 1) / group_size;
+ if weights.shape() != [vocab_size, model_dim / packing_divisor] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding lookup weights shape mismatch: got {:?}, expected [{}, {}]",
+ weights.shape(),
+ vocab_size,
+ model_dim / packing_divisor
+ )),
+ ));
+ }
+ if scales.shape() != [vocab_size, num_groups] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding lookup scales shape mismatch: got {:?}, expected [{}, {}]",
+ scales.shape(),
+ vocab_size,
+ num_groups
+ )),
+ ));
+ }
+ if scales.data_type() != data_type {
+ return Err(QuantizedEmbeddingError::UnsupportedDataType(
+ scales.data_type(),
+ ));
+ }
+
+ // Load or create biases buffer [vocab_size, num_groups] (MLX key: "biases")
+ let biases_buffer: MTLBuffer = match parameter_tree
+ .leaf("biases")
+ .or_else(|_| parameter_tree.leaf("output_biases"))
+ {
+ Ok(mut deq_biases) => {
+ if deq_biases.shape() != [vocab_size, num_groups] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding lookup deq_biases shape mismatch: got {:?}, expected [{}, {}]",
+ deq_biases.shape(),
+ vocab_size,
+ num_groups
+ )),
+ ));
+ }
+ if deq_biases.data_type() != data_type {
+ return Err(QuantizedEmbeddingError::UnsupportedDataType(
+ deq_biases.data_type(),
+ ));
+ }
+ unsafe { deq_biases.mtl_buffer().to_owned() }
+ },
+ Err(_) => {
+ let elem_size: usize = match data_type {
+ DataType::F16 | DataType::BF16 => 2,
+ DataType::F32 => 4,
+ other => {
+ return Err(
+ QuantizedEmbeddingError::UnsupportedDataType(other),
+ );
+ },
+ };
+ let size_bytes = (vocab_size * num_groups * elem_size) as u64;
+ let buf = mtl_context.device.new_buffer(
+ size_bytes,
+ metal::MTLResourceOptions::StorageModeShared,
+ );
+ unsafe {
+ std::ptr::write_bytes(
+ buf.contents(),
+ 0,
+ size_bytes as usize,
+ );
+ }
+ buf
+ },
+ };
+
+ let weights_buffer = unsafe { weights.mtl_buffer().to_owned() };
+ let scales_buffer = unsafe { scales.mtl_buffer().to_owned() };
+
+ Ok(Self {
+ kernel,
+ weights_buffer,
+ scales_buffer,
+ biases_buffer,
+ vocab_size: vocab_size as u32,
+ model_dim: model_dim as u32,
+ group_size: group_size as u32,
+ })
+ }
+}
+
+impl EncodableWithState for QuantizedEmbeddingLookupKernelBlock {
+ fn encode(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &CommandBuffer,
+ parameters: &EncodingParameters,
+ ) {
+ let arrays = state.arrays(&[ArrayId::TokenIds, ArrayId::Main]);
+ let batch_size = state.active_suffix_length();
+ let mut token_ids_array_mut = arrays[0].borrow_mut();
+ let mut output_array_mut = arrays[1].borrow_mut();
+
+ let token_ids_buffer = unsafe { token_ids_array_mut.mtl_buffer() };
+ let output_buffer = unsafe { output_array_mut.mtl_buffer() };
+
+ let root_command_buffer = command_buffer.root_command_buffer();
+ let encoder = root_command_buffer.new_compute_command_encoder();
+
+ let args = QuantizedEmbeddingLookupArguments {
+ token_ids_buffer,
+ weights_buffer: &self.weights_buffer,
+ scales_buffer: &self.scales_buffer,
+ biases_buffer: &self.biases_buffer,
+ output_buffer,
+ batch_size: batch_size as u32,
+ vocab_size: self.vocab_size,
+ model_dim: self.model_dim,
+ group_size: self.group_size,
+ };
+
+ self.kernel
+ .encode(encoder, args)
+ .expect("Failed to encode quantized embedding lookup kernel");
+
+ encoder.end_encoding();
+
+ if parameters.wait_until_completed {
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
+ }
+}
+
+// Quantized embedding readout block - uses quantized matmul for efficiency
+pub struct QuantizedEmbeddingReadoutKernelBlock {
+ kernel: super::super::kernel::quant_matmul::QuantizedMatmulKernel,
+ weights_buffer: MTLBuffer,
+ scales_buffer: MTLBuffer,
+ biases_buffer: MTLBuffer,
+ vocab_size: usize,
+ model_dim: usize,
+}
+
+impl QuantizedEmbeddingReadoutKernelBlock {
+ pub fn new(
+ mtl_context: &MTLContext,
+ data_type: DataType,
+ vocab_size: usize,
+ model_dim: usize,
+ group_size: usize,
+ mode: QuantizationMode,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+ ) -> Result<Self, QuantizedEmbeddingError> {
+ // Load weights [vocab_size, model_dim/2] as U8
+ let mut weights = match parameter_tree.leaf("weights") {
+ Ok(weights) => weights,
+ Err(_) => parameter_tree.leaf("output_weights").map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load weights: {:?}",
+ e
+ )))
+ })?,
+ };
+
+ // Load scales [vocab_size, num_groups]
+ let mut scales = match parameter_tree.leaf("scales") {
+ Ok(scales) => scales,
+ Err(_) => parameter_tree.leaf("output_scales").map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load scales: {:?}",
+ e
+ )))
+ })?,
+ };
+
+ // Validate shapes
+ let num_groups = (model_dim + group_size - 1) / group_size;
+ let packing_divisor = mode.packing_divisor();
+
+ // Determine if weights are transposed by checking shape
+ let weights_transposed = weights.shape()[0] == vocab_size;
+
+ if weights.shape() != [vocab_size, model_dim / packing_divisor] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding readout weights shape mismatch: got {:?}, expected [{}, {}]",
+ weights.shape(),
+ vocab_size,
+ model_dim / packing_divisor
+ )),
+ ));
+ }
+ if scales.shape() != [vocab_size, num_groups] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding readout scales shape mismatch: got {:?}, expected [{}, {}]",
+ scales.shape(),
+ vocab_size,
+ num_groups
+ )),
+ ));
+ }
+ if scales.data_type() != data_type {
+ return Err(QuantizedEmbeddingError::UnsupportedDataType(
+ scales.data_type(),
+ ));
+ }
+
+ // MLX requires per-group biases; if missing, create a zero buffer of shape [vocab_size, num_groups]
+ let biases_buffer: MTLBuffer = match parameter_tree
+ .leaf("biases")
+ .or_else(|_| parameter_tree.leaf("output_biases"))
+ {
+ Ok(mut deq_biases) => {
+ if deq_biases.shape() != [vocab_size, num_groups] {
+ return Err(QuantizedEmbeddingError::MetalError(
+ MTLError::Generic(format!(
+ "Embedding readout deq_biases shape mismatch: got {:?}, expected [{}, {}]",
+ deq_biases.shape(),
+ vocab_size,
+ num_groups
+ )),
+ ));
+ }
+ if deq_biases.data_type() != data_type {
+ return Err(QuantizedEmbeddingError::UnsupportedDataType(
+ deq_biases.data_type(),
+ ));
+ }
+ unsafe { deq_biases.mtl_buffer().to_owned() }
+ },
+ Err(_) => {
+ // Allocate zero-initialized biases buffer
+ let elem_size: usize = match data_type {
+ DataType::F16 | DataType::BF16 => 2,
+ DataType::F32 => 4,
+ other => {
+ return Err(
+ QuantizedEmbeddingError::UnsupportedDataType(other),
+ );
+ },
+ };
+ let size_bytes = (vocab_size * num_groups * elem_size) as u64;
+ let buf = mtl_context.device.new_buffer(
+ size_bytes,
+ metal::MTLResourceOptions::StorageModeShared,
+ );
+ unsafe {
+ std::ptr::write_bytes(
+ buf.contents(),
+ 0,
+ size_bytes as usize,
+ );
+ }
+ buf
+ },
+ };
+
+ let weights_buffer = unsafe { weights.mtl_buffer().to_owned() };
+ let scales_buffer = unsafe { scales.mtl_buffer().to_owned() };
+
+ use super::super::kernel::quant_matmul::{
+ QuantizationType, QuantizedMatmulKernel,
+ };
+
+ let kernel = QuantizedMatmulKernel::new(
+ mtl_context,
+ data_type,
+ group_size,
+ model_dim,
+ vocab_size,
+ mode,
+ QuantizationType::Mlx,
+ weights_transposed,
+ )
+ .map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to create kernel: {:?}",
+ e
+ )))
+ })?;
+
+ Ok(Self {
+ kernel,
+ weights_buffer,
+ scales_buffer,
+ biases_buffer,
+ vocab_size,
+ model_dim,
+ })
+ }
+}
+
+impl EncodableWithState for QuantizedEmbeddingReadoutKernelBlock {
+ fn encode(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &CommandBuffer,
+ parameters: &EncodingParameters,
+ ) {
+ let arrays = state.arrays(&[ArrayId::Main, ArrayId::Logits]);
+ let batch_size = state.active_suffix_length();
+ let mut input_array_mut = arrays[0].borrow_mut();
+ let mut output_array_mut = arrays[1].borrow_mut();
+
+ let input_buffer = unsafe { input_array_mut.mtl_buffer() };
+ let output_buffer = unsafe { output_array_mut.mtl_buffer() };
+
+ let root_command_buffer = command_buffer.root_command_buffer();
+ let encoder = root_command_buffer.new_compute_command_encoder();
+
+ // For transposed matmul: input @ weights.T
+ // where weights is [vocab_size, model_dim]
+ use super::super::kernel::quant_matmul::{
+ QuantizationType, QuantizedMatmulArguments,
+ };
+
+ let args = QuantizedMatmulArguments {
+ a_buffer: input_buffer,
+ b_buffer: &self.weights_buffer,
+ scales_buffer: &self.scales_buffer,
+ zero_points_or_biases_buffer: &self.biases_buffer,
+ output_buffer,
+ batch: batch_size as i32,
+ input_dim: self.model_dim as i32,
+ output_dim: self.vocab_size as i32,
+ quantization_type: QuantizationType::Mlx,
+ };
+
+ self.kernel
+ .encode(encoder, args)
+ .expect("Failed to encode quantized embedding readout kernel");
+
+ encoder.end_encoding();
+
+ if parameters.wait_until_completed {
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/embedding/quant_embedding.metal b/crates/uzu/src/backends/metal/kernel/embedding/quant_embedding.metal
new file mode 100644
index 000000000..76b5b3612
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/embedding/quant_embedding.metal
@@ -0,0 +1,183 @@
+#include <metal_stdlib>
+using namespace metal;
+
+template<typename T, uint PACKING_DIVISOR, bool SIGNED_STORAGE>
+[[kernel]] void quantized_embedding_lookup(
+ const device uint64_t* token_ids [[buffer(0)]], // [batch_size]
+ const device uint8_t* weights [[buffer(1)]], // [vocab_size, model_dim/packing_divisor] packed
+ const device T* scales [[buffer(2)]], // [vocab_size, num_groups]
+ const device T* biases [[buffer(3)]], // [vocab_size, num_groups]
+ device T* output [[buffer(4)]], // [batch_size, model_dim]
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+) {
+ const uint batch_idx = thread_position_in_grid / model_dim;
+ const uint dim_idx = thread_position_in_grid % model_dim;
+
+ if (batch_idx >= batch_size) return;
+
+ const uint64_t token_id = token_ids[batch_idx];
+ if (token_id >= vocab_size) {
+ output[thread_position_in_grid] = T(0);
+ return;
+ }
+
+ const uint group_idx = dim_idx / group_size;
+ const uint num_groups = (model_dim + group_size - 1) / group_size;
+
+ const T scale = scales[token_id * num_groups + group_idx];
+ const T bias = biases[token_id * num_groups + group_idx];
+
+ const uint weights_stride = model_dim / PACKING_DIVISOR;
+ const device uint8_t* weights_u8 = weights;
+ const device int8_t* weights_i8 =
+ reinterpret_cast<const device int8_t*>(weights);
+
+ int quantized_value = 0;
+ if (PACKING_DIVISOR == 2) {
+ const uint byte_idx =
+ token_id * weights_stride + (dim_idx / 2);
+ const uint8_t packed = weights_u8[byte_idx];
+ if ((dim_idx & 1) == 0) {
+ quantized_value = int(packed & 0x0F);
+ } else {
+ quantized_value = int((packed >> 4) & 0x0F);
+ }
+ } else {
+ const uint elem_idx = token_id * weights_stride + dim_idx;
+ quantized_value =
+ SIGNED_STORAGE ? int(weights_i8[elem_idx])
+ : int(weights_u8[elem_idx]);
+ }
+
+ output[thread_position_in_grid] = scale * T(quantized_value) + bias;
+}
+
+template [[host_name("quantized_embedding_lookup_f32_uint4")]]
+[[kernel]] void quantized_embedding_lookup<float, 2, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device float* scales [[buffer(2)]],
+ const device float* biases [[buffer(3)]],
+ device float* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_f16_uint4")]]
+[[kernel]] void quantized_embedding_lookup<half, 2, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device half* scales [[buffer(2)]],
+ const device half* biases [[buffer(3)]],
+ device half* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_bf16_uint4")]]
+[[kernel]] void quantized_embedding_lookup<bfloat, 2, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device bfloat* scales [[buffer(2)]],
+ const device bfloat* biases [[buffer(3)]],
+ device bfloat* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_f32_int8")]]
+[[kernel]] void quantized_embedding_lookup<float, 1, true>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device float* scales [[buffer(2)]],
+ const device float* biases [[buffer(3)]],
+ device float* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_f16_int8")]]
+[[kernel]] void quantized_embedding_lookup<half, 1, true>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device half* scales [[buffer(2)]],
+ const device half* biases [[buffer(3)]],
+ device half* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_bf16_int8")]]
+[[kernel]] void quantized_embedding_lookup<bfloat, 1, true>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device bfloat* scales [[buffer(2)]],
+ const device bfloat* biases [[buffer(3)]],
+ device bfloat* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_f32_uint8")]]
+[[kernel]] void quantized_embedding_lookup<float, 1, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device float* scales [[buffer(2)]],
+ const device float* biases [[buffer(3)]],
+ device float* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_f16_uint8")]]
+[[kernel]] void quantized_embedding_lookup<half, 1, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device half* scales [[buffer(2)]],
+ const device half* biases [[buffer(3)]],
+ device half* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
+
+template [[host_name("quantized_embedding_lookup_bf16_uint8")]]
+[[kernel]] void quantized_embedding_lookup<bfloat, 1, false>(
+ const device uint64_t* token_ids [[buffer(0)]],
+ const device uint8_t* weights [[buffer(1)]],
+ const device bfloat* scales [[buffer(2)]],
+ const device bfloat* biases [[buffer(3)]],
+ device bfloat* output [[buffer(4)]],
+ constant uint32_t& batch_size [[buffer(5)]],
+ constant uint32_t& vocab_size [[buffer(6)]],
+ constant uint32_t& model_dim [[buffer(7)]],
+ constant uint32_t& group_size [[buffer(8)]],
+ uint thread_position_in_grid [[thread_position_in_grid]]
+);
diff --git a/crates/uzu/src/backends/metal/kernel/linear/mod.rs b/crates/uzu/src/backends/metal/kernel/linear/mod.rs
index bc736dcd2..b28dc52bf 100644
--- a/crates/uzu/src/backends/metal/kernel/linear/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/linear/mod.rs
@@ -5,7 +5,9 @@ use mpsgraph::CommandBuffer as MPSCommandBuffer;
use super::{
KernelDataType, TensorAddBias,
- quant_matmul::{QuantizedMatmulArguments, QuantizedMatmulKernel},
+ quant_matmul::{
+ QuantizationType, QuantizedMatmulArguments, QuantizedMatmulKernel,
+ },
};
use crate::{
Array, DataType,
@@ -21,19 +23,15 @@ use crate::{
};
pub struct QuantizedLinearKernelBlock {
- kernel_mm: QuantizedMatmulKernel,
- kernel_mv: QuantizedMatmulKernel,
+ kernel: QuantizedMatmulKernel,
bias_add_kernel: Option<TensorAddBias>,
biases_buffer: Option<MTLBuffer>,
weights_buffer: MTLBuffer,
scales_buffer: MTLBuffer,
- zero_points_buffer: MTLBuffer,
+ zero_points_or_biases_buffer: MTLBuffer,
+ quantization_type: QuantizationType,
input_dim: usize,
output_dim: usize,
- #[allow(dead_code)]
- group_size: usize,
- #[allow(dead_code)]
- kernel_data_type: DataType,
input_array_id: ArrayId,
output_array_id: ArrayId,
}
@@ -50,7 +48,10 @@ impl QuantizedLinearKernelBlock {
) -> Result<Self, MTLError> {
let kernel_data_type: DataType = config.activation_precision.into();
- if !matches!(kernel_data_type, DataType::F16 | DataType::BF16) {
+ if !matches!(
+ kernel_data_type,
+ DataType::F16 | DataType::BF16 | DataType::F32
+ ) {
return Err(MTLError::Generic(format!(
"Unsupported data type for quantized kernel: {:?}",
kernel_data_type
@@ -61,9 +62,13 @@ impl QuantizedLinearKernelBlock {
MTLError::Generic(format!("Failed to load weights: {:?}", e))
})?;
- if weights.data_type() != DataType::U8 {
+ let packing_divisor = config.weight_quantization_mode.packing_divisor();
+ let storage_type = config.weight_quantization_mode.storage_type();
+
+ if weights.data_type() != storage_type {
return Err(MTLError::Generic(format!(
- "Expected packed U8 weights, got {:?}",
+ "Expected weights of type {:?}, got {:?}",
+ storage_type,
weights.data_type()
)));
}
@@ -71,32 +76,16 @@ impl QuantizedLinearKernelBlock {
let mut scales = parameter_tree.leaf("scales").map_err(|e| {
MTLError::Generic(format!("Failed to load scales: {:?}", e))
})?;
-
- let mut zero_points =
- parameter_tree.leaf("zero_points").map_err(|e| {
- MTLError::Generic(format!(
- "Failed to load zero_points: {:?}",
- e
- ))
- })?;
-
let k_g = (input_dim + config.group_size - 1) / config.group_size;
let w_shape = weights.shape();
let s_shape = scales.shape();
- let zp_shape = zero_points.shape();
- if !(w_shape == [output_dim, input_dim / 2]
- && s_shape == [output_dim, k_g]
- && zp_shape == [output_dim, (k_g + 1) / 2])
- {
- return Err(MTLError::Generic(format!(
- "Unexpected shapes. weights={:?}, scales={:?}, zero_points={:?}; expected [N,K/2],[N,K_g],[N,(K_g+1)/2]",
- w_shape, s_shape, zp_shape,
- )));
- }
+ // Determine if weights are transposed by checking shape
+ let weights_transposed = w_shape[0] == output_dim;
- let (scales_buffer, zero_points_buffer) = {
+ // Determine quantization style: prefer MLX (deq_biases), else AWQ (zero_points)
+ let (quantization_type, zero_points_or_biases_buffer, scales_buffer) = {
if scales.data_type() != kernel_data_type {
return Err(MTLError::Generic(format!(
"Scales dtype mismatch: got {:?}, expected {:?}",
@@ -104,10 +93,70 @@ impl QuantizedLinearKernelBlock {
kernel_data_type
)));
}
- let scales_buffer = unsafe { scales.mtl_buffer() }.to_owned();
- let zero_points_buffer =
- unsafe { zero_points.mtl_buffer() }.to_owned();
- (scales_buffer, zero_points_buffer)
+ match parameter_tree.leaf("deq_biases") {
+ Ok(mut deq_biases) => {
+ let db_shape = deq_biases.shape();
+ if !(w_shape == [output_dim, input_dim / packing_divisor]
+ && s_shape == [output_dim, k_g]
+ && db_shape == [output_dim, k_g])
+ {
+ return Err(MTLError::Generic(format!(
+ "Unexpected MLX shapes. weights={:?}, scales={:?}, deq_biases={:?}; expected [N,K/{}],[N,K_g],[N,K_g]",
+ w_shape, s_shape, db_shape, packing_divisor
+ )));
+ }
+ if deq_biases.data_type() != kernel_data_type {
+ return Err(MTLError::Generic(format!(
+ "deq_biases dtype mismatch: got {:?}, expected {:?}",
+ deq_biases.data_type(),
+ kernel_data_type
+ )));
+ }
+ let scales_buffer =
+ unsafe { scales.mtl_buffer() }.to_owned();
+ let biases_buf =
+ unsafe { deq_biases.mtl_buffer() }.to_owned();
+ (QuantizationType::Mlx, biases_buf, scales_buffer)
+ },
+ Err(_) => {
+ let mut zero_points =
+ parameter_tree.leaf("zero_points").map_err(|e| {
+ MTLError::Generic(format!(
+ "Failed to load zero_points: {:?}",
+ e
+ ))
+ })?;
+ let zp_shape = zero_points.shape();
+ let expected_zp_entries =
+ (k_g + packing_divisor - 1) / packing_divisor;
+ if !(w_shape == [output_dim, input_dim / packing_divisor]
+ && s_shape == [output_dim, k_g]
+ && zp_shape == [output_dim, expected_zp_entries])
+ {
+ return Err(MTLError::Generic(format!(
+ "Unexpected AWQ shapes. weights={:?}, scales={:?}, zero_points={:?}; expected [N,K/{}],[N,K_g],[N,(K_g+{})/{}]",
+ w_shape,
+ s_shape,
+ zp_shape,
+ packing_divisor,
+ packing_divisor - 1,
+ packing_divisor
+ )));
+ }
+ if zero_points.data_type() != storage_type {
+ return Err(MTLError::Generic(format!(
+ "Zero-points dtype mismatch: got {:?}, expected {:?}",
+ zero_points.data_type(),
+ storage_type
+ )));
+ }
+ let scales_buffer =
+ unsafe { scales.mtl_buffer() }.to_owned();
+ let zps_buf =
+ unsafe { zero_points.mtl_buffer() }.to_owned();
+ (QuantizationType::ZeroPoint, zps_buf, scales_buffer)
+ },
+ }
};
let weights_buffer: MTLBuffer =
@@ -143,58 +192,30 @@ impl QuantizedLinearKernelBlock {
};
let g = config.group_size;
- let (kernel_name_mm, kernel_name_mv) = match (kernel_data_type, g) {
- (DataType::F16, 32) => {
- ("qmm_transposed_f16_g32_b4", "qmv_f16_g32_b4")
- },
- (DataType::F16, 64) => {
- ("qmm_transposed_f16_g64_b4", "qmv_f16_g64_b4")
- },
- (DataType::F16, 128) => {
- ("qmm_transposed_f16_g128_b4", "qmv_f16_g128_b4")
- },
- (DataType::BF16, 32) => {
- ("qmm_transposed_bf16_g32_b4", "qmv_bf16_g32_b4")
- },
- (DataType::BF16, 64) => {
- ("qmm_transposed_bf16_g64_b4", "qmv_bf16_g64_b4")
- },
- (DataType::BF16, 128) => {
- ("qmm_transposed_bf16_g128_b4", "qmv_bf16_g128_b4")
- },
- (dtype, other) => {
- return Err(MTLError::Generic(format!(
- "Unsupported group size {} for transposed {:?} kernel",
- other, dtype
- )));
- },
- };
+ let mode = config.weight_quantization_mode;
- let kernel_mm = QuantizedMatmulKernel::new(
- mtl_context,
- kernel_data_type,
- kernel_name_mm,
- )
- .map_err(|e| MTLError::Generic(format!("{:?}", e)))?;
- let kernel_mv = QuantizedMatmulKernel::new(
+ let kernel = QuantizedMatmulKernel::new(
mtl_context,
kernel_data_type,
- kernel_name_mv,
+ g,
+ input_dim,
+ output_dim,
+ mode,
+ quantization_type,
+ weights_transposed,
)
.map_err(|e| MTLError::Generic(format!("{:?}", e)))?;
Ok(Self {
- kernel_mm,
- kernel_mv,
+ kernel,
bias_add_kernel,
biases_buffer,
weights_buffer,
scales_buffer,
- zero_points_buffer,
+ zero_points_or_biases_buffer,
+ quantization_type,
input_dim,
output_dim,
- group_size: config.group_size,
- kernel_data_type,
input_array_id,
output_array_id,
})
@@ -206,14 +227,10 @@ impl EncodableWithState for QuantizedLinearKernelBlock {
&self,
state: &mut ForwardPassState,
command_buffer: &MPSCommandBuffer,
- _parameters: &EncodingParameters,
+ parameters: &EncodingParameters,
) {
let arrays = state.arrays(&[self.input_array_id, self.output_array_id]);
- let input_array = arrays[0].borrow();
-
- let batch_size = input_array.shape()[0];
-
- drop(input_array);
+ let batch_size = state.active_suffix_length();
let mut input_array_mut = arrays[0].borrow_mut();
let mut output_array_mut = arrays[1].borrow_mut();
@@ -224,29 +241,19 @@ impl EncodableWithState for QuantizedLinearKernelBlock {
let root_command_buffer = command_buffer.root_command_buffer();
let encoder = root_command_buffer.new_compute_command_encoder();
- let m = batch_size;
- let n = self.output_dim;
- let k = self.input_dim;
-
let args = QuantizedMatmulArguments {
a_buffer: input_buffer,
b_buffer: &self.weights_buffer,
scales_buffer: &self.scales_buffer,
- zero_points_buffer: &self.zero_points_buffer,
+ zero_points_or_biases_buffer: &self.zero_points_or_biases_buffer,
output_buffer: output_buffer,
- m: m as i32,
- n: n as i32,
- k: k as i32,
- };
-
- let use_gemv = batch_size == 1;
- let kernel = if use_gemv {
- &self.kernel_mv
- } else {
- &self.kernel_mm
+ batch: batch_size as i32,
+ input_dim: self.input_dim as i32,
+ output_dim: self.output_dim as i32,
+ quantization_type: self.quantization_type,
};
- kernel
+ self.kernel
.encode(encoder, args)
.expect("Failed to encode quantized matmul kernel");
@@ -266,5 +273,12 @@ impl EncodableWithState for QuantizedLinearKernelBlock {
&retained_cb,
);
}
+
+ if parameters.wait_until_completed {
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
}
}
diff --git a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
index 61af0f929..f0f038d5a 100644
--- a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
@@ -89,10 +89,13 @@ impl MlpGateActMulKernel {
fn act_code(act: &Activation) -> u16 {
match act {
- Activation::SILU {
+ Activation::SiLU {
..
} => 0,
- Activation::GELU => 1,
+ Activation::Gelu => 1,
+ Activation::Identity => {
+ panic!("Identity activation is not supported for MLP kernels")
+ },
}
}
@@ -157,10 +160,10 @@ impl EncodableWithState for MlpBlockEncodable {
&self,
state: &mut ForwardPassState,
command_buffer: &MPSCommandBuffer,
- _params: &EncodingParameters,
+ params: &EncodingParameters,
) {
// Up
- self.up.encode(state, command_buffer, _params);
+ self.up.encode(state, command_buffer, params);
// Gate act+mul (fused_up -> hidden)
let arrays = state.arrays(&[ArrayId::MlpFusedUp, ArrayId::MlpHidden]);
let mut fused = arrays[0].borrow_mut();
@@ -177,6 +180,13 @@ impl EncodableWithState for MlpBlockEncodable {
drop(fused);
drop(hidden);
// Down
- self.down.encode(state, command_buffer, _params);
+ self.down.encode(state, command_buffer, params);
+
+ if params.wait_until_completed {
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
}
}
diff --git a/crates/uzu/src/backends/metal/kernel/mod.rs b/crates/uzu/src/backends/metal/kernel/mod.rs
index e68739bf1..83ab64e71 100644
--- a/crates/uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/mod.rs
@@ -1,5 +1,6 @@
pub mod attention;
mod data_type;
+pub mod embedding;
pub mod kv_cache_update;
pub mod linear;
pub mod media_kernels;
@@ -9,6 +10,7 @@ pub mod quant_matmul;
pub mod rms_norm;
pub mod rope;
pub mod sampling;
+pub mod ssm;
mod tensor_add_bias;
mod tensor_add_swap;
mod tensor_copy;
@@ -31,6 +33,13 @@ pub use rms_norm::{
};
pub use rope::{RopeKernel, RopeKernelEncodable};
pub use sampling::{SamplingKernel, SamplingKernelEncodable};
+pub(crate) use ssm::MambaMixerEncodable;
+pub use ssm::{
+ Conv1dPackArguments, Conv1dScanArguments, Conv1dScanKernel,
+ SSDPrefillArguments, SSDPrefillKernel, SSDPrefillMode, SSDUpdateArguments,
+ SSDUpdateKernel, SSMKernelError, SSMUpdateArguments, SSMUpdateKernel,
+ SplitInProjArguments, SplitInProjKernel,
+};
pub use tensor_add_bias::TensorAddBias;
pub use tensor_add_swap::TensorAddSwap;
pub use tensor_copy::TensorCopy;
diff --git a/crates/uzu/src/backends/metal/kernel/moe/encodable.rs b/crates/uzu/src/backends/metal/kernel/moe/encodable.rs
index 3a8bf1b93..4124a597c 100644
--- a/crates/uzu/src/backends/metal/kernel/moe/encodable.rs
+++ b/crates/uzu/src/backends/metal/kernel/moe/encodable.rs
@@ -95,6 +95,11 @@ impl MoeBlockEncodable {
"Quantized router with fused router+topk not yet supported"
);
},
+ LinearConfig::MLXQuantized(_) => {
+ unimplemented!(
+ "MLX quantized router with fused router+topk not yet supported"
+ );
+ },
LinearConfig::FullPrecision {
..
} => {
@@ -278,10 +283,13 @@ impl MoeBlockEncodable {
fn gating_code_from_activation(activation: &Activation) -> u32 {
match activation {
- Activation::GELU => 3,
- Activation::SILU {
+ Activation::Gelu => 3,
+ Activation::SiLU {
..
} => 2,
+ Activation::Identity => {
+ panic!("Identity activation is not supported for MoE kernels")
+ },
}
}
}
@@ -293,7 +301,7 @@ impl EncodableWithState for MoeBlockEncodable {
command_buffer: &MPSCommandBuffer,
parameters: &EncodingParameters,
) {
- let suffix_length = state.aux_buffers_suffix_length();
+ let suffix_length = state.active_suffix_length();
let arrays = state.arrays(&[
ArrayId::Main,
ArrayId::MoeTopkIds,
diff --git a/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs b/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs
index 984492117..122401609 100644
--- a/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs
@@ -1,4 +1,4 @@
-use std::mem::size_of;
+use std::{collections::HashMap, mem::size_of};
use metal::{
Buffer as MTLBuffer, ComputeCommandEncoderRef,
@@ -6,7 +6,15 @@ use metal::{
};
use super::super::MTLContext;
-use crate::{DataType, backends::metal::MTLError};
+use crate::{DataType, backends::metal::MTLError, config::QuantizationMode};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum QuantizationType {
+ /// GroupQuantized style: uses zero-points
+ ZeroPoint,
+ /// MLX style: uses pre-computed biases
+ Mlx,
+}
#[derive(Debug, thiserror::Error)]
pub enum QuantizedMatmulError {
@@ -22,50 +30,139 @@ pub enum QuantizedMatmulError {
n: usize,
k: usize,
},
+ #[error("Unsupported bits: {0}")]
+ UnsupportedBits(usize),
}
pub struct QuantizedMatmulKernel {
- pipeline: MTLComputePipelineState,
- kind: KernelKind,
+ pipelines: HashMap<KernelKind, (MTLComputePipelineState, u64, u64)>,
+ output_dim: usize,
+ weights_transposed: bool,
}
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct QuantizedMatmulArguments<'a> {
- pub a_buffer: &'a MTLBuffer, // Input A (float)
- pub b_buffer: &'a MTLBuffer, // Input B (quantized)
+ pub a_buffer: &'a MTLBuffer,
+ pub b_buffer: &'a MTLBuffer,
pub scales_buffer: &'a MTLBuffer,
- pub zero_points_buffer: &'a MTLBuffer,
+ pub zero_points_or_biases_buffer: &'a MTLBuffer,
pub output_buffer: &'a MTLBuffer,
- pub m: i32,
- pub n: i32,
- pub k: i32,
+ pub batch: i32,
+ pub input_dim: i32,
+ pub output_dim: i32,
+ pub quantization_type: QuantizationType,
+}
+
+fn dtype_suffix(data_type: DataType) -> Option<&'static str> {
+ match data_type {
+ DataType::F16 => Some("f16"),
+ DataType::BF16 => Some("bf16"),
+ DataType::F32 => Some("f32"),
+ _ => None,
+ }
+}
+
+fn base_qmm_kernel_name(
+ type_suffix: &str,
+ group_size: usize,
+ transpose_infix: &str,
+ bits: usize,
+) -> Result<String, QuantizedMatmulError> {
+ if bits != 4 && bits != 8 {
+ return Err(QuantizedMatmulError::UnsupportedBits(bits));
+ }
+
+ let kernel_name = match (type_suffix, group_size) {
+ ("f16", 32) => format!("qmm{}_f16_g32_b{}", transpose_infix, bits),
+ ("f16", 64) => format!("qmm{}_f16_g64_b{}", transpose_infix, bits),
+ ("f16", 128) => format!("qmm{}_f16_g128_b{}", transpose_infix, bits),
+ ("bf16", 32) => format!("qmm{}_bf16_g32_b{}", transpose_infix, bits),
+ ("bf16", 64) => format!("qmm{}_bf16_g64_b{}", transpose_infix, bits),
+ ("bf16", 128) => format!("qmm{}_bf16_g128_b{}", transpose_infix, bits),
+ ("f32", 32) => format!("qmm{}_f32_g32_b{}", transpose_infix, bits),
+ ("f32", 64) => format!("qmm{}_f32_g64_b{}", transpose_infix, bits),
+ ("f32", 128) => format!("qmm{}_f32_g128_b{}", transpose_infix, bits),
+ _ => {
+ return Err(QuantizedMatmulError::UnsupportedGroupSize(group_size));
+ },
+ };
+ Ok(kernel_name)
}
impl QuantizedMatmulKernel {
pub fn new(
mtl_context: &MTLContext,
data_type: DataType,
- kernel_name: &str,
+ group_size: usize,
+ input_dim: usize,
+ output_dim: usize,
+ mode: QuantizationMode,
+ quantization_type: QuantizationType,
+ weights_transposed: bool,
) -> Result<Self, QuantizedMatmulError> {
- if !matches!(data_type, DataType::F16 | DataType::BF16) {
+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)
+ {
return Err(QuantizedMatmulError::UnsupportedDataType(data_type));
}
- let pipeline = mtl_context
- .compute_pipeline_state(kernel_name, None)
+ let function_constants = metal::FunctionConstantValues::new();
+ let use_mlx_quant = matches!(quantization_type, QuantizationType::Mlx);
+ function_constants.set_constant_value_at_index(
+ &use_mlx_quant as *const bool as *const std::ffi::c_void,
+ metal::MTLDataType::Bool,
+ 40,
+ );
+
+ let mut pipelines = HashMap::new();
+
+ let kernel_name_mv = select_matrix_vector_kernel_name(
+ data_type,
+ group_size,
+ weights_transposed,
+ output_dim,
+ input_dim,
+ mode,
+ )?;
+
+ let (pipeline_mv, _) = mtl_context
+ .compute_pipeline_state_with_reflection(
+ &kernel_name_mv,
+ Some(&function_constants),
+ )
.map_err(QuantizedMatmulError::MetalError)?;
+ pipelines.insert(KernelKind::MatrixVector, (pipeline_mv, 32, 32));
+
+ let kernel_name_mm = select_qmm_kernel_name(
+ data_type,
+ group_size,
+ weights_transposed,
+ output_dim,
+ input_dim,
+ mode,
+ )?;
- let kind = if kernel_name.starts_with("qmv") {
- KernelKind::Qmv
- } else if kernel_name.starts_with("qvm") {
- KernelKind::Qvm
+ let (pipeline_mm, _) = mtl_context
+ .compute_pipeline_state_with_reflection(
+ &kernel_name_mm,
+ Some(&function_constants),
+ )
+ .map_err(QuantizedMatmulError::MetalError)?;
+
+ let (bm, bn) = if kernel_name_mm.contains("_64x64") {
+ (64, 64)
+ } else if kernel_name_mm.contains("_64x128") {
+ (64, 128)
+ } else if kernel_name_mm.contains("_128x64") {
+ (128, 64)
} else {
- KernelKind::Qmm
+ (32, 32)
};
+ pipelines.insert(KernelKind::MatrixMatrix, (pipeline_mm, bm, bn));
Ok(Self {
- pipeline,
- kind,
+ pipelines,
+ output_dim,
+ weights_transposed,
})
}
@@ -74,6 +171,7 @@ impl QuantizedMatmulKernel {
let type_suffix = match data_type {
DataType::F16 => "f16",
DataType::BF16 => "bf16",
+ DataType::F32 => "f32",
_ => unreachable!(),
};
@@ -85,66 +183,68 @@ impl QuantizedMatmulKernel {
encoder: &ComputeCommandEncoderRef,
args: QuantizedMatmulArguments,
) -> Result<(), QuantizedMatmulError> {
- encoder.set_compute_pipeline_state(&self.pipeline);
+ let variant = self.select_variant(args.batch as usize);
+ let (pipeline, bm, bn) =
+ self.pipelines.get(&variant).ok_or_else(|| {
+ QuantizedMatmulError::InvalidDimensions {
+ m: args.batch as usize,
+ n: args.output_dim as usize,
+ k: args.input_dim as usize,
+ }
+ })?;
+
+ encoder.set_compute_pipeline_state(pipeline);
// Set buffers
encoder.set_buffer(0, Some(args.b_buffer), 0);
encoder.set_buffer(1, Some(args.scales_buffer), 0);
- encoder.set_buffer(2, Some(args.zero_points_buffer), 0);
+ encoder.set_buffer(2, Some(args.zero_points_or_biases_buffer), 0);
encoder.set_buffer(3, Some(args.a_buffer), 0);
encoder.set_buffer(4, Some(args.output_buffer), 0);
- // Set constants
+ let k: i32 = args.input_dim;
+ let m = args.batch;
+ let n = args.output_dim;
+
encoder.set_bytes(
5,
size_of::<i32>() as u64,
- &args.k as *const i32 as *const _,
+ &k as *const i32 as *const _,
);
encoder.set_bytes(
6,
size_of::<i32>() as u64,
- &args.n as *const i32 as *const _,
+ &n as *const i32 as *const _,
);
encoder.set_bytes(
7,
size_of::<i32>() as u64,
- &args.m as *const i32 as *const _,
+ &m as *const i32 as *const _,
);
- match self.kind {
- KernelKind::Qmv => {
+ match variant {
+ KernelKind::MatrixVector => {
let bk = 32;
- let bn = 8;
- let n_tgp_y = (args.n + bn - 1) / bn; // ceiling division
- let threadgroups =
- MTLSize::new(args.m as u64, n_tgp_y as u64, 1);
+ let bn = if self.weights_transposed {
+ 8
+ } else {
+ 64
+ };
+ let n_tgp_y = (n + bn - 1) / bn;
+ let threadgroups = MTLSize::new(m as u64, n_tgp_y as u64, 1);
let threads_per_threadgroup = MTLSize::new(bk as u64, 2, 1);
encoder.dispatch_thread_groups(
threadgroups,
threads_per_threadgroup,
);
},
- KernelKind::Qvm => {
- let bk = 32;
- let bn = 64;
- let n_tgp_y = (args.n + bn - 1) / bn; // ceiling division for columns
- let threadgroups =
- MTLSize::new(args.m as u64, n_tgp_y as u64, 1);
- let threads_per_threadgroup = MTLSize::new(bk as u64, 2, 1);
- encoder.dispatch_thread_groups(
- threadgroups,
- threads_per_threadgroup,
- );
- },
- KernelKind::Qmm => {
- let bm = 32;
- let bn = 32;
+ KernelKind::MatrixMatrix => {
let wm = 2;
let wn = 2;
let threads_per_threadgroup = MTLSize::new(32, wn, wm);
let threadgroups = MTLSize::new(
- (args.n as u64 + bn - 1) / bn,
- (args.m as u64 + bm - 1) / bm,
+ (n as u64 + bn - 1) / bn,
+ (m as u64 + bm - 1) / bm,
1,
);
encoder.dispatch_thread_groups(
@@ -156,51 +256,81 @@ impl QuantizedMatmulKernel {
Ok(())
}
+
+ fn select_variant(
+ &self,
+ batch: usize,
+ ) -> KernelKind {
+ if batch < 32 || self.output_dim == 1 {
+ KernelKind::MatrixVector
+ } else {
+ KernelKind::MatrixMatrix
+ }
+ }
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum KernelKind {
- Qmm,
- Qmv,
- Qvm,
+fn select_matrix_vector_kernel_name(
+ data_type: DataType,
+ group_size: usize,
+ weights_transposed: bool,
+ output_dim: usize,
+ input_dim: usize,
+ mode: QuantizationMode,
+) -> Result<String, QuantizedMatmulError> {
+ let type_suffix = dtype_suffix(data_type)
+ .ok_or(QuantizedMatmulError::UnsupportedDataType(data_type))?;
+ let bits = match mode {
+ QuantizationMode::UInt4 => 4,
+ QuantizationMode::UInt8 | QuantizationMode::Int8 => 8,
+ };
+
+ if weights_transposed {
+ let mut name = format!("qmv_{}_g{}_b{}", type_suffix, group_size, bits);
+ if output_dim % 8 == 0 && input_dim % 512 == 0 {
+ name.push_str("_fast");
+ }
+ return Ok(name);
+ }
+
+ Ok(format!("qvm_{}_g{}_b{}", type_suffix, group_size, bits))
}
-pub fn encode_quantized_matmul(
- mtl_context: &MTLContext,
- encoder: &ComputeCommandEncoderRef,
- kernel_data_type: DataType,
+fn select_qmm_kernel_name(
+ data_type: DataType,
group_size: usize,
- transpose: bool,
- args: QuantizedMatmulArguments,
-) -> Result<(), QuantizedMatmulError> {
- let type_suffix = match kernel_data_type {
- DataType::F16 => "f16",
- DataType::BF16 => "bf16",
- other => return Err(QuantizedMatmulError::UnsupportedDataType(other)),
+ weights_transposed: bool,
+ output_dim: usize,
+ input_dim: usize,
+ mode: QuantizationMode,
+) -> Result<String, QuantizedMatmulError> {
+ let type_suffix = dtype_suffix(data_type)
+ .ok_or(QuantizedMatmulError::UnsupportedDataType(data_type))?;
+ let bits = match mode {
+ QuantizationMode::UInt4 => 4,
+ QuantizationMode::Int8 | QuantizationMode::UInt8 => 8,
};
- let kernel_name = match (type_suffix, group_size, transpose) {
- ("f16", 32, false) => "qmm_f16_g32_b4".to_string(),
- ("f16", 32, true) => "qmm_transposed_f16_g32_b4".to_string(),
- ("f16", 64, false) => "qmm_f16_g64_b4".to_string(),
- ("f16", 64, true) => "qmm_transposed_f16_g64_b4".to_string(),
- ("f16", 128, false) => "qmm_f16_g128_b4".to_string(),
- ("f16", 128, true) => "qmm_transposed_f16_g128_b4".to_string(),
- ("bf16", 32, false) => "qmm_bf16_g32_b4".to_string(),
- ("bf16", 32, true) => "qmm_transposed_bf16_g32_b4".to_string(),
- ("bf16", 64, false) => "qmm_bf16_g64_b4".to_string(),
- ("bf16", 64, true) => "qmm_transposed_bf16_g64_b4".to_string(),
- ("bf16", 128, false) => "qmm_bf16_g128_b4".to_string(),
- ("bf16", 128, true) => "qmm_transposed_bf16_g128_b4".to_string(),
- _ => {
- return Err(QuantizedMatmulError::UnsupportedGroupSize(group_size));
- },
+ let transpose_infix = if weights_transposed {
+ "_transposed"
+ } else {
+ ""
};
+ let mut kernel_name =
+ base_qmm_kernel_name(type_suffix, group_size, transpose_infix, bits)?;
+ if weights_transposed {
+ if output_dim % 32 != 0 {
+ kernel_name.push_str("_unaligned");
+ } else if type_suffix == "bf16" && group_size == 128 && bits == 4 {
+ kernel_name.push_str("_64x64");
+ }
+ } else if input_dim % 32 == 0 {
+ kernel_name.push_str("_alignedk");
+ }
+ Ok(kernel_name)
+}
- let kernel = QuantizedMatmulKernel::new(
- mtl_context,
- kernel_data_type,
- &kernel_name,
- )?;
- kernel.encode(encoder, args)
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum KernelKind {
+ MatrixMatrix,
+ MatrixVector,
}
diff --git a/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal b/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal
index 61b00e1b6..46b5150b4 100644
--- a/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal
+++ b/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal
@@ -5,6 +5,10 @@ using namespace metal;
#include "mma.h"
+// Function constant: true = MLX-style (pre-computed biases), false = AWQ-style (zero-points)
+constant bool kUseMlxQuant [[function_constant(40)]];
+constant bool kUseZeroPoints = !kUseMlxQuant;
+
template <int bits, int wsize = 8>
inline constexpr short get_pack_factor() {
@@ -19,42 +23,79 @@ inline constexpr short get_bytes_per_pack() {
template <typename T, typename U, int values_per_thread, int bits>
inline U load_vector(const device T* x, thread U* x_thread) {
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
U sum = 0;
- for (int i = 0; i < values_per_thread; i += 4) {
- sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3];
- x_thread[i] = x[i];
- x_thread[i + 1] = x[i + 1] / 16.0f;
- x_thread[i + 2] = x[i + 2] / 256.0f;
- x_thread[i + 3] = x[i + 3] / 4096.0f;
+ if (bits == 4) {
+ for (int i = 0; i < values_per_thread; i += 4) {
+ sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3];
+ x_thread[i] = x[i];
+ x_thread[i + 1] = x[i + 1] / 16.0f;
+ x_thread[i + 2] = x[i + 2] / 256.0f;
+ x_thread[i + 3] = x[i + 3] / 4096.0f;
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < values_per_thread; i++) {
+ sum += x[i];
+ x_thread[i] = x[i];
+ }
}
return sum;
}
template <typename T, typename U, int values_per_thread, int bits>
inline U load_vector_safe(const device T* x, thread U* x_thread, int N) {
- static_assert(bits == 4, "Only int4 supported");
-
- const U scale_lut[4] = {
- static_cast<U>(1.0f),
- static_cast<U>(1.0f / 16.0f),
- static_cast<U>(1.0f / 256.0f),
- static_cast<U>(1.0f / 4096.0f)
- };
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
U sum = 0;
- for (int i = 0; i < values_per_thread; ++i) {
- x_thread[i] = 0;
- }
- for (int i = 0; i < N; ++i) {
- U v = x[i];
- sum += v;
- x_thread[i] = v * scale_lut[i & 3];
+ if (bits == 4) {
+ const U scale_lut[4] = {
+ static_cast<U>(1.0f),
+ static_cast<U>(1.0f / 16.0f),
+ static_cast<U>(1.0f / 256.0f),
+ static_cast<U>(1.0f / 4096.0f)
+ };
+
+ for (int i = 0; i < values_per_thread; ++i) {
+ x_thread[i] = 0;
+ }
+ for (int i = 0; i < N; ++i) {
+ U v = x[i];
+ sum += v;
+ x_thread[i] = v * scale_lut[i & 3];
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; ++i) {
+ U v = x[i];
+ sum += v;
+ x_thread[i] = v;
+ }
+ for (int i = N; i < values_per_thread; ++i) {
+ x_thread[i] = 0;
+ }
}
return sum;
}
+template <typename U, int values_per_thread, int bits>
+inline void
+qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) {
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
+
+ if (bits == 4) {
+ U s[2] = {scale, scale / 16.0f};
+ for (int i = 0; i < (values_per_thread / 2); i++) {
+ result[2 * i] += x * (s[0] * (w[i] & 0x0f) + bias);
+ result[2 * i + 1] += x * (s[1] * (w[i] & 0xf0) + bias);
+ }
+ }
+ else if (bits == 8) {
+ for (int i = 0; i < values_per_thread; i++) {
+ result[i] += x * (scale * w[i] + bias);
+ }
+ }
+}
+
template <typename U, int values_per_thread, int bits>
inline U qdot(
const device uint8_t* w,
@@ -62,20 +103,61 @@ inline U qdot(
U scale,
U bias,
U sum) {
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
U accum = 0;
- const device uint16_t* ws = (const device uint16_t*)w;
- for (int i = 0; i < (values_per_thread / 4); i++) {
- accum +=
- (x_thread[4 * i] * (ws[i] & 0x000f) +
- x_thread[4 * i + 1] * (ws[i] & 0x00f0) +
- x_thread[4 * i + 2] * (ws[i] & 0x0f00) +
- x_thread[4 * i + 3] * (ws[i] & 0xf000));
+ if (bits == 4) {
+ const device uint16_t* ws = (const device uint16_t*)w;
+ for (int i = 0; i < (values_per_thread / 4); i++) {
+ accum +=
+ (x_thread[4 * i] * (ws[i] & 0x000f) +
+ x_thread[4 * i + 1] * (ws[i] & 0x00f0) +
+ x_thread[4 * i + 2] * (ws[i] & 0x0f00) +
+ x_thread[4 * i + 3] * (ws[i] & 0xf000));
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < values_per_thread; i++) {
+ accum += x_thread[i] * w[i];
+ }
}
return scale * accum + sum * bias;
}
+template <typename U, int values_per_thread, int bits>
+inline U qdot_zero_point(
+ const device uint8_t* w,
+ const thread U* x_thread,
+ U scale,
+ U zero_point) {
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
+
+ U accum = 0;
+ if (bits == 4) {
+ const device uint16_t* ws = (const device uint16_t*)w;
+ const uint16_t zp0 = static_cast<uint16_t>(zero_point);
+ const uint16_t zp1 = static_cast<uint16_t>(zero_point) << 4;
+ const uint16_t zp2 = static_cast<uint16_t>(zero_point) << 8;
+ const uint16_t zp3 = static_cast<uint16_t>(zero_point) << 12;
+
+ for (int i = 0; i < (values_per_thread / 4); i++) {
+ uint16_t word = ws[i];
+ accum += x_thread[4 * i] *
+ static_cast<U>(static_cast<int>(word & 0x000f) - static_cast<int>(zp0));
+ accum += x_thread[4 * i + 1] *
+ static_cast<U>(static_cast<int>(word & 0x00f0) - static_cast<int>(zp1));
+ accum += x_thread[4 * i + 2] *
+ static_cast<U>(static_cast<int>(word & 0x0f00) - static_cast<int>(zp2));
+ accum += x_thread[4 * i + 3] *
+ static_cast<U>(static_cast<int>(word & 0xf000) - static_cast<int>(zp3));
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < values_per_thread; i++) {
+ accum += x_thread[i] * (static_cast<U>(w[i]) - zero_point);
+ }
+ }
+ return scale * accum;
+}
+
template <typename U, int values_per_thread, int bits>
inline U qdot_safe(
const device uint8_t* w,
@@ -84,27 +166,33 @@ inline U qdot_safe(
U bias,
U sum,
int N) {
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
U accum = 0;
- const device uint16_t* ws = (const device uint16_t*)w;
-
- int full = N / 4;
- for (int i = 0; i < full; i++) {
- accum +=
- (x_thread[4 * i] * (ws[i] & 0x000f) +
- x_thread[4 * i + 1] * (ws[i] & 0x00f0) +
- x_thread[4 * i + 2] * (ws[i] & 0x0f00) +
- x_thread[4 * i + 3] * (ws[i] & 0xf000));
- }
+ if (bits == 4) {
+ const device uint16_t* ws = (const device uint16_t*)w;
+
+ int full = N / 4;
+ for (int i = 0; i < full; i++) {
+ accum +=
+ (x_thread[4 * i] * (ws[i] & 0x000f) +
+ x_thread[4 * i + 1] * (ws[i] & 0x00f0) +
+ x_thread[4 * i + 2] * (ws[i] & 0x0f00) +
+ x_thread[4 * i + 3] * (ws[i] & 0xf000));
+ }
- int rem = N & 3;
- if (rem > 0) {
- uint16_t wv = ws[full];
- int base = 4 * full;
- if (rem > 0) accum += x_thread[base] * (wv & 0x000f);
- if (rem > 1) accum += x_thread[base + 1] * (wv & 0x00f0);
- if (rem > 2) accum += x_thread[base + 2] * (wv & 0x0f00);
+ int rem = N & 3;
+ if (rem > 0) {
+ uint16_t wv = ws[full];
+ int base = 4 * full;
+ if (rem > 0) accum += x_thread[base] * (wv & 0x000f);
+ if (rem > 1) accum += x_thread[base + 1] * (wv & 0x00f0);
+ if (rem > 2) accum += x_thread[base + 2] * (wv & 0x0f00);
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; i++) {
+ accum += x_thread[i] * w[i];
+ }
}
return scale * accum + sum * bias;
@@ -112,28 +200,61 @@ inline U qdot_safe(
template <typename U, int N, int bits>
inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) {
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
- U s[2] = {scale, scale / static_cast<U>(16.0f)};
- for (int i = 0; i < (N / 2); i++) {
- w_local[2 * i] = s[0] * (w[i] & 0x0f) + bias;
- w_local[2 * i + 1] = s[1] * (w[i] & 0xf0) + bias;
+ if (bits == 4) {
+ U s[2] = {scale, scale / static_cast<U>(16.0f)};
+ for (int i = 0; i < (N / 2); i++) {
+ w_local[2 * i] = s[0] * (w[i] & 0x0f) + bias;
+ w_local[2 * i + 1] = s[1] * (w[i] & 0xf0) + bias;
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; i++) {
+ w_local[i] = scale * w[i] + bias;
+ }
}
}
+template <>
+inline void dequantize<bfloat, 8, 4>(const device uint8_t* w, bfloat scale, bfloat bias, threadgroup bfloat* w_local) {
+ const device uint32_t* w_ptr = (const device uint32_t*)w;
+ uint32_t packed = *w_ptr;
+
+ bfloat4 v0, v1;
+
+ // Low 4 nibbles
+ v0.x = static_cast<bfloat>(packed & 0xF);
+ v0.y = static_cast<bfloat>((packed >> 4) & 0xF);
+ v0.z = static_cast<bfloat>((packed >> 8) & 0xF);
+ v0.w = static_cast<bfloat>((packed >> 12) & 0xF);
+
+ // High 4 nibbles
+ v1.x = static_cast<bfloat>((packed >> 16) & 0xF);
+ v1.y = static_cast<bfloat>((packed >> 20) & 0xF);
+ v1.z = static_cast<bfloat>((packed >> 24) & 0xF);
+ v1.w = static_cast<bfloat>((packed >> 28) & 0xF);
+
+ v0 = v0 * scale + bias;
+ v1 = v1 * scale + bias;
+
+ threadgroup bfloat4* out_ptr = (threadgroup bfloat4*)w_local;
+ out_ptr[0] = v0;
+ out_ptr[1] = v1;
+}
+
template <
typename T,
short BROWS,
- short BCOLS,
+ short BCOLS,
short dst_ld,
short reduction_dim,
short tgp_size,
short group_size,
short bits>
-struct QuantizedBlockLoader {
+struct QuantizedBlockLoaderMlx {
static_assert(BCOLS <= group_size, "Group size should be larger than columns");
static_assert(group_size % BCOLS == 0, "Group size should be divisible by columns");
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
UZU_MTL_CONST short pack_factor = get_pack_factor<bits, 8>();
UZU_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>();
@@ -144,7 +265,6 @@ struct QuantizedBlockLoader {
const int src_ld;
const int tile_stride;
short group_step_cnt;
- int k_base;
const int group_stride;
const short thread_idx;
@@ -156,7 +276,7 @@ struct QuantizedBlockLoader {
const device T* scales;
const device T* biases;
- QuantizedBlockLoader(
+ QuantizedBlockLoaderMlx(
const device uint8_t* src_,
const device T* scales_,
const device T* biases_,
@@ -196,40 +316,9 @@ struct QuantizedBlockLoader {
return;
}
- if (reduction_dim == 1) {
- // N-tail: zero out rows beyond valid outputs
- if (bi >= src_tile_dim.x) {
- for (int i = 0; i < n_reads * pack_factor; i++) {
- dst[i] = T(0);
- }
- return;
- }
-
- // K-tail: strictly limit to valid packs and zero trailing nibbles
- int valid_cols = src_tile_dim.y; // 0..BK
- int valid_packs = (valid_cols + pack_factor - 1) / pack_factor;
-
- T scale;
- T bias;
- current_scale_bias(scale, bias);
- for (int i = 0; i < n_reads; i++) {
- int pack_idx = bj + i; // global pack index across the BK packs
- if (pack_idx < valid_packs) {
- dequantize<T, pack_factor, bits>(
- src + i * bytes_per_pack, scale, bias, dst + i * pack_factor);
- if (pack_idx == valid_packs - 1) {
- int rem = valid_cols - (valid_packs - 1) * pack_factor;
- if (rem > 0 && rem < pack_factor) {
- for (int r = rem; r < pack_factor; ++r) {
- dst[i * pack_factor + r] = T(0);
- }
- }
- }
- } else {
- for (int j = 0; j < pack_factor; ++j) {
- dst[i * pack_factor + j] = T(0);
- }
- }
+ if (reduction_dim == 1 && bi >= src_tile_dim.x) {
+ for (int i = 0; i < n_reads * pack_factor; i++) {
+ dst[i] = T(0);
}
return;
}
@@ -245,7 +334,10 @@ struct QuantizedBlockLoader {
T bias = *biases;
for (int i = 0; i < n_reads; i++) {
dequantize<T, pack_factor, bits>(
- src + i * bytes_per_pack, scale, bias, dst + i * pack_factor);
+ (device uint8_t*)(src + i * bytes_per_pack),
+ scale,
+ bias,
+ dst + i * pack_factor);
}
}
@@ -270,7 +362,6 @@ struct QuantizedBlockLoader {
}
};
-// Loader that computes bias from packed zero-points (U8) and scales on-GPU
template <
typename T,
short BROWS,
@@ -279,11 +370,12 @@ template <
short reduction_dim,
short tgp_size,
short group_size,
- short bits>
+ short bits,
+ bool per_output_layout = false>
struct QuantizedBlockLoaderZp {
static_assert(BCOLS <= group_size, "Group size should be larger than columns");
static_assert(group_size % BCOLS == 0, "Group size should be divisible by columns");
- static_assert(bits == 4, "Only int4 supported");
+ static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
UZU_MTL_CONST short pack_factor = get_pack_factor<bits, 8>();
UZU_MTL_CONST short bytes_per_pack = get_bytes_per_pack<bits>();
@@ -307,6 +399,9 @@ struct QuantizedBlockLoaderZp {
const device T* scales;
const device T* scales_row_start;
const device uint8_t* zps_row_start;
+ const int out_group_base;
+ const int out_groups_total;
+ const int zp_stride_total;
QuantizedBlockLoaderZp(
const device uint8_t* src_,
@@ -316,7 +411,10 @@ struct QuantizedBlockLoaderZp {
const int groups_per_row_,
threadgroup T* dst_,
ushort simd_group_id [[simdgroup_index_in_threadgroup]],
- ushort simd_lane_id [[thread_index_in_simdgroup]])
+ ushort simd_lane_id [[thread_index_in_simdgroup]],
+ const int out_group_base_ = 0,
+ const int out_groups_total_ = 0,
+ const int zp_stride_total_ = 0)
: src_ld(src_ld_),
groups_per_row(groups_per_row_),
tile_stride(
@@ -332,16 +430,40 @@ struct QuantizedBlockLoaderZp {
src(src_ + bi * src_ld * bytes_per_pack / pack_factor + bj * bytes_per_pack),
scales(reduction_dim == 1 ? (scales_ + bi * groups_per_row_) : scales_),
scales_row_start(reduction_dim == 1 ? (scales_ + bi * groups_per_row_) : scales_),
- zps_row_start(reduction_dim == 1 ? (zero_points_row_start_ + bi * ((groups_per_row_ + 1) / 2))
- : zero_points_row_start_) {}
+ zps_row_start(reduction_dim == 1
+ ? (zero_points_row_start_ + bi * (bits == 4 ? ((groups_per_row_ + 1) / 2) : groups_per_row_))
+ : zero_points_row_start_),
+ out_group_base(per_output_layout ? out_group_base_ : 0),
+ out_groups_total(per_output_layout ? out_groups_total_ : 0),
+ zp_stride_total(per_output_layout ? zp_stride_total_ : 0) {}
inline void current_scale_bias(thread T& out_scale, thread T& out_bias) const {
- int g = reduction_dim == 0 ? (k_base / group_size)
- : (int)(scales - scales_row_start);
- const device uint8_t* zp_ptr = zps_row_start + (g >> 1);
- uint8_t zp_b = *zp_ptr;
- uint zp_n = (g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F);
- T scale_val = reduction_dim == 0 ? scales_row_start[g] : *scales;
+ uint zp_n;
+ T scale_val;
+ if (per_output_layout) {
+ const int row_idx = k_base + bi;
+ const int scale_index = row_idx * groups_per_row + out_group_base;
+ scale_val = scales_row_start[scale_index];
+ if (bits == 4) {
+ const int byte_index = row_idx * zp_stride_total + (out_group_base >> 1);
+ uint8_t zp_b = zps_row_start[byte_index];
+ zp_n = (out_group_base & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F);
+ } else {
+ const int zp_index = row_idx * zp_stride_total + out_group_base;
+ zp_n = zps_row_start[zp_index];
+ }
+ } else {
+ int g = reduction_dim == 0 ? (k_base / group_size)
+ : (int)(scales - scales_row_start);
+ scale_val = reduction_dim == 0 ? scales_row_start[g] : *scales;
+ if (bits == 4) {
+ const device uint8_t* zp_ptr = zps_row_start + (g >> 1);
+ uint8_t zp_b = *zp_ptr;
+ zp_n = (g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F);
+ } else {
+ zp_n = zps_row_start[g];
+ }
+ }
out_scale = scale_val;
out_bias = static_cast<T>(-scale_val * static_cast<T>(zp_n));
}
@@ -365,9 +487,41 @@ struct QuantizedBlockLoaderZp {
return;
}
- if (reduction_dim == 1 && bi >= src_tile_dim.x) {
- for (int i = 0; i < n_reads * pack_factor; i++) {
- dst[i] = T(0);
+ if (reduction_dim == 1) {
+ // N-tail: zero out rows beyond valid outputs
+ if (bi >= src_tile_dim.x) {
+ for (int i = 0; i < n_reads * pack_factor; i++) {
+ dst[i] = T(0);
+ }
+ return;
+ }
+
+ int valid_cols = src_tile_dim.y; // 0..BK
+ int valid_packs = (valid_cols + pack_factor - 1) / pack_factor;
+
+ T scale;
+ T bias;
+ current_scale_bias(scale, bias);
+ for (int i = 0; i < n_reads; i++) {
+ int pack_idx = bj + i; // global pack index across the BK packs
+ if (pack_idx < valid_packs) {
+ dequantize<T, pack_factor, bits>(
+ src + i * bytes_per_pack, scale, bias, dst + i * pack_factor);
+
+ // Mask the last pack if needed
+ if (pack_idx == valid_packs - 1) {
+ int rem = valid_cols - pack_idx * pack_factor;
+ if (rem < pack_factor) {
+ for (int r = rem; r < pack_factor; ++r) {
+ dst[i * pack_factor + r] = T(0);
+ }
+ }
+ }
+ } else {
+ for (int j = 0; j < pack_factor; ++j) {
+ dst[i * pack_factor + j] = T(0);
+ }
+ }
}
return;
}
@@ -406,10 +560,101 @@ struct QuantizedBlockLoaderZp {
}
};
+template <
+ typename LoaderW,
+ typename LoaderX,
+ typename Mma,
+ typename T,
+ const bool aligned_K,
+ const int BM,
+ const int BK,
+ const int BN>
+inline void qmm_core(
+ thread LoaderX& loader_x,
+ thread LoaderW& loader_w,
+ thread Mma& mma_op,
+ const short num_els,
+ const short num_outs,
+ const int K,
+ device T* y,
+ const constant int& N,
+ threadgroup T* Xs,
+ threadgroup T* Ws,
+ uint lid [[thread_index_in_threadgroup]]) {
+ if (num_els < BM) {
+ if ((K % BK) != 0) {
+ const int k_blocks = K / BK;
+ for (int k = 0; k < k_blocks; k++) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_safe(short2(BK, num_els));
+ loader_w.load_unsafe();
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ loader_x.next();
+ loader_w.next();
+ }
+ const short num_k = K - k_blocks * BK;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_safe(short2(num_k, num_els));
+ loader_w.load_safe(short2(BN, num_k));
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ } else {
+ for (int k = 0; k < K; k += BK) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_safe(short2(BK, num_els));
+ loader_w.load_unsafe();
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ loader_x.next();
+ loader_w.next();
+ }
+ }
+ } else {
+ if ((K % BK) != 0) {
+ const int k_blocks = K / BK;
+ for (int k = 0; k < k_blocks; k++) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_unsafe();
+ loader_w.load_unsafe();
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ loader_x.next();
+ loader_w.next();
+ }
+ const short num_k = K - k_blocks * BK;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_safe(short2(num_k, BM));
+ loader_w.load_safe(short2(BN, num_k));
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ } else {
+ for (int k = 0; k < K; k += BK) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ loader_x.load_unsafe();
+ loader_w.load_unsafe();
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(Xs, Ws);
+ loader_x.next();
+ loader_w.next();
+ }
+ }
+ }
+
+ // Store results to device memory
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (num_els < BM) {
+ mma_op.store_result_safe(y, N, short2(BN, num_els));
+ } else {
+ mma_op.store_result(y, N);
+ }
+}
+
template <
typename T,
const int group_size,
const int bits,
+ const bool aligned_K = false,
const int BM = 32,
const int BK = 32,
const int BN = 32>
@@ -417,6 +662,7 @@ void qmm_impl(
const device uint32_t* w,
const device T* scales,
const device uint8_t* zero_points,
+ const device T* biases,
const device T* x,
device T* y,
threadgroup T* Xs,
@@ -443,15 +689,6 @@ void qmm_impl(
using mma_t = matmul_utils::BlockMMA<T, T, BM, BN, BK, WM, WN, false, false, BK_padded, BN_padded>;
using loader_x_t = matmul_utils::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * 32, 1, 4>;
- using loader_w_t = QuantizedBlockLoaderZp<
- T,
- BK,
- BN,
- BN_padded,
- 0,
- WM * WN * 32,
- group_size,
- bits>;
auto wl = (const device uint8_t*)w;
@@ -459,35 +696,79 @@ void qmm_impl(
const int y_col = tid.x * BN;
x += y_row * static_cast<int64_t>(K);
wl += y_col * bytes_per_pack / pack_factor;
- const int groups_per_row = (K + group_size - 1) / group_size;
- scales += y_col * groups_per_row;
- const device uint8_t* zps_row_start = zero_points + y_col * ((groups_per_row + 1) / 2);
y += y_row * static_cast<int64_t>(N) + y_col;
+ const device T* scales_base = scales;
+ const device T* biases_base = biases;
+
const short num_els = min(BM, M - y_row);
const short num_outs = min(BN, N - y_col);
loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid);
- loader_w_t loader_w(wl, scales, zps_row_start, N, groups_per_row, Ws, simd_gid, simd_lid);
mma_t mma_op(simd_gid, simd_lid);
+ if (kUseMlxQuant) {
+ using loader_w_t = QuantizedBlockLoaderMlx<T, BK, BN, BN_padded, 0, WM * WN * 32, group_size, bits>;
+ const device T* scales_mlx = scales_base + (y_col / group_size);
+ const device T* biases_mlx = biases_base + (y_col / group_size);
+ loader_w_t loader_w(wl, scales_mlx, biases_mlx, N, Ws, simd_gid, simd_lid);
+ qmm_core<loader_w_t, loader_x_t, mma_t, T, aligned_K, BM, BK, BN>(
+ loader_x, loader_w, mma_op, num_els, num_outs, K, y, N, Xs, Ws, lid);
+ } else {
+ const int out_groups_total = (N + group_size - 1) / group_size;
+ const int groups_per_row = out_groups_total;
+ const int out_group = y_col / group_size;
+ const int zp_stride_out =
+ (bits == 4) ? ((out_groups_total + 1) / 2) : out_groups_total;
+ using loader_w_t = QuantizedBlockLoaderZp<T, BK, BN, BN_padded, 0, WM * WN * 32, group_size, bits, true>;
+ loader_w_t loader_w(
+ wl,
+ scales_base,
+ zero_points,
+ N,
+ groups_per_row,
+ Ws,
+ simd_gid,
+ simd_lid,
+ out_group,
+ out_groups_total,
+ zp_stride_out);
+ qmm_core<loader_w_t, loader_x_t, mma_t, T, aligned_K, BM, BK, BN>(
+ loader_x, loader_w, mma_op, num_els, num_outs, K, y, N, Xs, Ws, lid);
+ }
+}
+
+template <
+ typename LoaderW,
+ typename LoaderX,
+ typename Mma,
+ typename T,
+ const bool aligned_N,
+ const int BM,
+ const int BK,
+ const int BN>
+inline void qmm_transposed_core(
+ thread LoaderX& loader_x,
+ thread LoaderW& loader_w,
+ thread Mma& mma_op,
+ const short num_els,
+ const short num_outs,
+ const int K,
+ device T* y,
+ const constant int& N,
+ threadgroup T* Xs,
+ threadgroup T* Ws,
+ uint lid [[thread_index_in_threadgroup]]) {
if (num_els < BM) {
- if ((K % BK) != 0) {
- const int k_blocks = K / BK;
- for (int k = 0; k < k_blocks; k++) {
+ if (!aligned_N && num_outs < BN) {
+ for (int k = 0; k < K; k += BK) {
threadgroup_barrier(mem_flags::mem_threadgroup);
loader_x.load_safe(short2(BK, num_els));
- loader_w.load_unsafe();
+ loader_w.load_safe(short2(BK, num_outs));
threadgroup_barrier(mem_flags::mem_threadgroup);
mma_op.mma(Xs, Ws);
loader_x.next();
loader_w.next();
}
- const short num_k = K - k_blocks * BK;
- threadgroup_barrier(mem_flags::mem_threadgroup);
- loader_x.load_safe(short2(num_k, num_els));
- loader_w.load_safe(short2(BN, num_k));
- threadgroup_barrier(mem_flags::mem_threadgroup);
- mma_op.mma(Xs, Ws);
} else {
for (int k = 0; k < K; k += BK) {
threadgroup_barrier(mem_flags::mem_threadgroup);
@@ -500,29 +781,23 @@ void qmm_impl(
}
}
} else {
- if ((K % BK) != 0) {
- const int k_blocks = K / BK;
- for (int k = 0; k < k_blocks; k++) {
+ if (!aligned_N && num_outs < BN) {
+ for (int k = 0; k < K; k += BK) {
threadgroup_barrier(mem_flags::mem_threadgroup);
loader_x.load_unsafe();
- loader_w.load_unsafe();
+ loader_w.load_safe(short2(BK, num_outs));
threadgroup_barrier(mem_flags::mem_threadgroup);
mma_op.mma(Xs, Ws);
loader_x.next();
loader_w.next();
}
- const short num_k = K - k_blocks * BK;
- threadgroup_barrier(mem_flags::mem_threadgroup);
- loader_x.load_safe(short2(num_k, BM));
- loader_w.load_safe(short2(BN, num_k));
- threadgroup_barrier(mem_flags::mem_threadgroup);
- mma_op.mma(Xs, Ws);
} else {
for (int k = 0; k < K; k += BK) {
threadgroup_barrier(mem_flags::mem_threadgroup);
loader_x.load_unsafe();
loader_w.load_unsafe();
threadgroup_barrier(mem_flags::mem_threadgroup);
+
mma_op.mma(Xs, Ws);
loader_x.next();
loader_w.next();
@@ -530,6 +805,7 @@ void qmm_impl(
}
}
+ // Store results to device memory
threadgroup_barrier(mem_flags::mem_threadgroup);
if (num_els < BM || num_outs < BN) {
mma_op.store_result_safe(y, N, short2(num_outs, num_els));
@@ -550,6 +826,7 @@ void qmm_transposed_impl(
const device uint32_t* w,
const device T* scales,
const device uint8_t* zero_points,
+ const device T* biases,
const device T* x,
device T* y,
threadgroup T* Xs,
@@ -564,26 +841,14 @@ void qmm_transposed_impl(
static_assert(BK >= 32, "BK should be larger than SIMD_SIZE");
static_assert(BK % 32 == 0, "BK should be divisible by SIMD_SIZE");
- (void)lid;
-
constexpr int WM = 2;
constexpr int WN = 2;
constexpr int pack_factor = get_pack_factor<bits, 8>();
constexpr int bytes_per_pack = get_bytes_per_pack<bits>();
-
constexpr int BK_padded = (BK + 16 / sizeof(T));
using mma_t = matmul_utils::BlockMMA<T, T, BM, BN, BK, WM, WN, false, true, BK_padded, BK_padded>;
using loader_x_t = matmul_utils::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * 32>;
- using loader_w_t = QuantizedBlockLoaderZp<
- T,
- BN,
- BK,
- BK_padded,
- 1,
- WM * WN * 32,
- group_size,
- bits>;
const int K_w = K * bytes_per_pack / pack_factor;
const int K_g = (K + group_size - 1) / group_size;
@@ -592,49 +857,37 @@ void qmm_transposed_impl(
auto wl = (const device uint8_t*)w;
- x += y_row * static_cast<int64_t>(K);
- wl += y_col * K_w;
+ const device T* x_block = x + y_row * static_cast<int64_t>(K);
+ const device uint8_t* w_block = wl + y_col * K_w;
scales += y_col * K_g;
- const device uint8_t* zps_row_start = zero_points + y_col * ((K_g + 1) / 2);
- y += y_row * static_cast<int64_t>(N) + y_col;
+ biases += y_col * K_g;
+ device T* y_block = y + y_row * static_cast<int64_t>(N) + y_col;
const short num_els = min(BM, M - y_row);
const short num_outs = min(BN, N - y_col);
- loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid);
- loader_w_t loader_w(wl, scales, zps_row_start, K, K_g, Ws, simd_gid, simd_lid);
+ loader_x_t loader_x(x_block, K, Xs, simd_gid, simd_lid);
mma_t mma_op(simd_gid, simd_lid);
- const int k_blocks = (K + BK - 1) / BK;
- for (int kb = 0; kb < k_blocks; kb++) {
- const short k_len = (kb < (K / BK)) ? BK : static_cast<short>(K - (K / BK) * BK);
- threadgroup_barrier(mem_flags::mem_threadgroup);
- if (num_els < BM || k_len < BK) {
- loader_x.load_safe(short2(k_len, num_els));
- } else {
- loader_x.load_unsafe();
- }
- loader_w.load_safe(short2(num_outs, k_len));
- threadgroup_barrier(mem_flags::mem_threadgroup);
- mma_op.mma(Xs, Ws);
- if (kb + 1 < k_blocks) {
- loader_x.next();
- loader_w.next();
- }
- }
-
- threadgroup_barrier(mem_flags::mem_threadgroup);
- if (num_els < BM || num_outs < BN) {
- mma_op.store_result_safe(y, N, short2(num_outs, num_els));
+ if (kUseMlxQuant) {
+ using loader_w_t = QuantizedBlockLoaderMlx< T, BN, BK, BK_padded, 1, WM * WN * 32, group_size, bits>;
+ loader_w_t loader_w(w_block, scales, biases, K, Ws, simd_gid, simd_lid);
+ qmm_transposed_core<loader_w_t, loader_x_t, mma_t, T, aligned_N, BM, BK, BN>(
+ loader_x, loader_w, mma_op, num_els, num_outs, K, y_block, N, Xs, Ws, lid);
} else {
- mma_op.store_result(y, N);
+ using loader_w_t = QuantizedBlockLoaderZp<T, BN, BK, BK_padded, 1, WM * WN * 32, group_size, bits>;
+ const device uint8_t* zero_points_row = zero_points + y_col * (bits == 4 ? ((K_g + 1) / 2) : K_g);
+ loader_w_t loader_w(w_block, scales, zero_points_row, K, K_g, Ws, simd_gid, simd_lid);
+ qmm_transposed_core<loader_w_t, loader_x_t, mma_t, T, aligned_N, BM, BK, BN>(
+ loader_x, loader_w, mma_op, num_els, num_outs, K, y_block, N, Xs, Ws, lid);
}
}
-template <typename T, int group_size, int bits>
-void qmv_impl(
+template <typename T, int group_size, int bits, bool UseMlx>
+void qmv_impl_dispatch(
const device uint32_t* w,
const device T* scales,
const device uint8_t* zero_points,
+ const device T* biases,
const device T* x,
device T* y,
const constant int& K, // in_vec_size
@@ -659,6 +912,8 @@ void qmv_impl(
const int in_vec_size_w = K * bytes_per_pack / pack_factor;
const int in_vec_size_g = (K + group_size - 1) / group_size; // ceil(K / group_size)
+ const device T* scales_base = scales;
+ const device uint8_t* zero_points_base = zero_points;
const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + simd_gid * results_per_simdgroup;
const int used_out_row = min(N - results_per_simdgroup, out_row);
@@ -669,7 +924,16 @@ void qmv_impl(
if (N < (num_simdgroups * results_per_simdgroup)) {
ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack;
scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread;
- const device uint8_t* zps_row_base = zero_points + out_row * ((in_vec_size_g + 1) / 2);
+
+ const int zp_stride = bits == 4 ? ((in_vec_size_g + 1) / 2) : in_vec_size_g;
+ const device uint8_t* zps_row_base = nullptr;
+ const device T* biases_row_base = nullptr;
+ if (UseMlx) {
+ biases_row_base = biases + out_row * in_vec_size_g;
+ } else {
+ zps_row_base = zero_points + out_row * zp_stride;
+ }
+
x += tid.x * K + simd_lid * values_per_thread;
y += tid.x * N + out_row;
@@ -680,14 +944,27 @@ void qmv_impl(
for (int row = 0; out_row + row < N; row++) {
if (row >= results_per_simdgroup) break;
auto wl = (const device uint8_t*)(ws + row * in_vec_size_w);
- const device T* sl = scales + row * in_vec_size_g;
- const device uint8_t* zl = zps_row_base + row * ((in_vec_size_g + 1) / 2);
+ const int row_idx = out_row + row;
+ const device T* sr = scales_base + row_idx * in_vec_size_g;
int g = (k + simd_lid * values_per_thread) / group_size;
- U s = sl[0];
- uint8_t zp_b = zl[g >> 1];
- U b = static_cast<U>(-s * static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F)));
- result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ U s = static_cast<U>(sr[g]);
+ if (UseMlx) {
+ const device T* bl = biases_row_base + row * in_vec_size_g;
+ U b = static_cast<U>(bl[g]);
+ result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ } else {
+ const device uint8_t* zl = zps_row_base + row * zp_stride;
+ U zp;
+ if (bits == 4) {
+ uint8_t zp_b = zl[g >> 1];
+ zp = static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F));
+ } else {
+ zp = static_cast<U>(zl[g]);
+ }
+ result[row] +=
+ qdot_zero_point<U, values_per_thread, bits>(wl, x_thread, s, zp);
+ }
}
ws += block_size * bytes_per_pack / pack_factor;
@@ -705,15 +982,27 @@ void qmv_impl(
for (int row = 0; out_row + row < N; row++) {
if (row >= results_per_simdgroup) break;
auto wl = (const device uint8_t*)(ws + row * in_vec_size_w);
- const device T* sl = scales + row * in_vec_size_g;
- const device uint8_t* zl = zps_row_base + row * ((in_vec_size_g + 1) / 2);
+ const int row_idx = out_row + row;
+ const device T* sr = scales_base + row_idx * in_vec_size_g;
int g = (k + simd_lid * values_per_thread) / group_size;
- U s = sl[0];
- uint8_t zp_b = zl[g >> 1];
- U b = static_cast<U>(-s * static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F)));
- result[row] +=
- qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ U s = static_cast<U>(sr[g]);
+ if (UseMlx) {
+ const device T* bl = biases_row_base + row * in_vec_size_g;
+ U b = static_cast<U>(bl[g]);
+ result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ } else {
+ const device uint8_t* zl = zps_row_base + row * zp_stride;
+ U zp;
+ if (bits == 4) {
+ uint8_t zp_b = zl[g >> 1];
+ zp = static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F));
+ } else {
+ zp = static_cast<U>(zl[g]);
+ }
+ result[row] += qdot_zero_point<U, values_per_thread, bits>(
+ wl, x_thread, s, zp);
+ }
}
}
@@ -728,7 +1017,16 @@ void qmv_impl(
else {
ws += used_out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack;
scales += used_out_row * in_vec_size_g + simd_lid / scale_step_per_thread;
- const device uint8_t* zps_row_base = zero_points + used_out_row * ((in_vec_size_g + 1) / 2);
+
+ const int zp_stride = bits == 4 ? ((in_vec_size_g + 1) / 2) : in_vec_size_g;
+ const device uint8_t* zps_row_base = nullptr;
+ const device T* biases_row_base = nullptr;
+ if (UseMlx) {
+ biases_row_base = biases + used_out_row * in_vec_size_g;
+ } else {
+ zps_row_base = zero_points + used_out_row * zp_stride;
+ }
+
x += tid.x * K + simd_lid * values_per_thread;
y += tid.x * N + used_out_row;
@@ -738,14 +1036,27 @@ void qmv_impl(
for (int row = 0; row < results_per_simdgroup; row++) {
auto wl = (const device uint8_t*)(ws + row * in_vec_size_w);
- const device T* sl = scales + row * in_vec_size_g;
- const device uint8_t* zl = zps_row_base + row * ((in_vec_size_g + 1) / 2);
+ const int row_idx = used_out_row + row;
+ const device T* sr = scales_base + row_idx * in_vec_size_g;
int g = (k + simd_lid * values_per_thread) / group_size;
- U s = sl[0];
- uint8_t zp_b = zl[g >> 1];
- U b = static_cast<U>(-s * static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F)));
- result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ U s = static_cast<U>(sr[g]);
+ if (UseMlx) {
+ const device T* bl = biases_row_base + row * in_vec_size_g;
+ U b = static_cast<U>(bl[g]);
+ result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ } else {
+ const device uint8_t* zl = zps_row_base + row * zp_stride;
+ U zp;
+ if (bits == 4) {
+ uint8_t zp_b = zl[g >> 1];
+ zp = static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F));
+ } else {
+ zp = static_cast<U>(zl[g]);
+ }
+ result[row] +=
+ qdot_zero_point<U, values_per_thread, bits>(wl, x_thread, s, zp);
+ }
}
ws += block_size * bytes_per_pack / pack_factor;
@@ -763,15 +1074,28 @@ void qmv_impl(
for (int row = 0; row < results_per_simdgroup; row++) {
auto wl = (const device uint8_t*)(ws + row * in_vec_size_w);
- const device T* sl = scales + row * in_vec_size_g;
- const device uint8_t* zl = zps_row_base + row * ((in_vec_size_g + 1) / 2);
+ const int row_idx = used_out_row + row;
+ const device T* sr = scales_base + row_idx * in_vec_size_g;
int g = (k + simd_lid * values_per_thread) / group_size;
- U s = sl[0];
- uint8_t zp_b = zl[g >> 1];
- U b = static_cast<U>(-s * static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F)));
- result[row] += qdot_safe<U, values_per_thread, bits>(
- wl, x_thread, s, b, sum, remaining);
+ U s = static_cast<U>(sr[g]);
+ if (UseMlx) {
+ const device T* bl = biases_row_base + row * in_vec_size_g;
+ U b = static_cast<U>(bl[g]);
+ result[row] += qdot_safe<U, values_per_thread, bits>(
+ wl, x_thread, s, b, sum, remaining);
+ } else {
+ const device uint8_t* zl = zps_row_base + row * zp_stride;
+ U zp;
+ if (bits == 4) {
+ uint8_t zp_b = zl[g >> 1];
+ zp = static_cast<U>((g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F));
+ } else {
+ zp = static_cast<U>(zl[g]);
+ }
+ result[row] += qdot_zero_point<U, values_per_thread, bits>(
+ wl, x_thread, s, zp);
+ }
}
}
@@ -785,86 +1109,297 @@ void qmv_impl(
}
template <typename T, int group_size, int bits>
-void qvm_impl(
+void qmv_impl(
const device uint32_t* w,
const device T* scales,
const device uint8_t* zero_points,
+ const device T* biases,
const device T* x,
device T* y,
- const constant int& K, // in_vec_size
- const constant int& N, // out_vec_size
+ const constant int& K,
+ const constant int& N,
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
+ if (kUseMlxQuant) {
+ qmv_impl_dispatch<T, group_size, bits, true>(
+ w, scales, zero_points, biases, x, y, K, N, tid, simd_gid, simd_lid);
+ } else {
+ qmv_impl_dispatch<T, group_size, bits, false>(
+ w, scales, zero_points, biases, x, y, K, N, tid, simd_gid, simd_lid);
+ }
+}
- typedef float U;
- constexpr int BN = 64;
- constexpr int BK = 32;
- constexpr int WN = 2;
+template <typename T, int group_size, int bits>
+void qmv_fast_impl(
+ const device uint32_t* w,
+ const device T* scales,
+ const device uint8_t* zero_points,
+ const device T* biases,
+ const device T* x,
+ device T* y,
+ const constant int& in_vec_size,
+ const constant int& out_vec_size,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int packs_per_thread = bits == 2 ? 1 : 2;
+ constexpr int num_simdgroups = 2;
+ constexpr int results_per_simdgroup = 4;
constexpr int pack_factor = get_pack_factor<bits, 32>();
constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>();
+ constexpr int values_per_thread = pack_factor * packs_per_thread;
+ constexpr int block_size = values_per_thread * SIMD_SIZE;
+ constexpr int scale_step_per_thread = group_size / values_per_thread;
+ const device uint8_t* ws = (const device uint8_t*)w;
+ typedef float U;
+ thread U x_thread[values_per_thread];
+ thread U result[results_per_simdgroup] = {0};
- const int lidy = simd_gid;
- const int lidx = simd_lid;
- const int bn = BN / WN;
+ const int in_vec_size_w = in_vec_size * bytes_per_pack / pack_factor;
+ const int in_vec_size_g = in_vec_size / group_size;
+ const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) +
+ simd_gid * results_per_simdgroup;
+ ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack;
+ scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread;
+
+ int zp_stride = 0;
+ const device uint8_t* zps = nullptr;
+ bool high_nibble = false;
+
+ if (kUseMlxQuant) {
+ biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread;
+ } else {
+ if (bits == 4) {
+ zp_stride = (in_vec_size_g + 1) / 2;
+ zps = zero_points + out_row * zp_stride;
+ int g_offset = simd_lid / scale_step_per_thread;
+ zps += g_offset / 2;
+ high_nibble = (g_offset & 1);
+ } else {
+ zp_stride = in_vec_size_g;
+ zps = zero_points + out_row * zp_stride;
+ zps += simd_lid / scale_step_per_thread;
+ }
+ }
- const int out_col = tid.y * BN + lidy * bn;
- const int in_row = tid.x;
+ x += tid.x * in_vec_size + simd_lid * values_per_thread;
+ y += tid.x * out_vec_size + out_row;
- if (out_col >= N) {
- return;
+ for (int k = 0; k < in_vec_size; k += block_size) {
+ U sum = load_vector<T, U, values_per_thread, bits>(x, x_thread);
+
+ for (int row = 0; row < results_per_simdgroup; row++) {
+ auto wl = (const device uint8_t*)(ws + row * in_vec_size_w);
+ const device T* sl = scales + row * in_vec_size_g;
+ U s = sl[0];
+
+ if (kUseMlxQuant) {
+ const device T* bl = biases + row * in_vec_size_g;
+ U b = bl[0];
+ result[row] += qdot<U, values_per_thread, bits>(wl, x_thread, s, b, sum);
+ } else {
+ const device uint8_t* zl = zps + row * zp_stride;
+ uint8_t zp_byte = *zl;
+ U zp = static_cast<U>((bits == 4 && high_nibble) ? (zp_byte >> 4) : (zp_byte & 0x0F));
+ if (bits == 8) zp = static_cast<U>(zp_byte);
+ result[row] += qdot_zero_point<U, values_per_thread, bits>(wl, x_thread, s, zp);
+ }
+ }
+
+ ws += block_size * bytes_per_pack / pack_factor;
+ scales += block_size / group_size;
+ if (kUseMlxQuant) {
+ biases += block_size / group_size;
+ } else {
+ if (bits == 4) {
+ zps += (block_size / group_size) / 2;
+ } else {
+ zps += block_size / group_size;
+ }
+ }
+ x += block_size;
+ }
+
+ for (int row = 0; row < results_per_simdgroup; row++) {
+ result[row] = simd_sum(result[row]);
+ if (simd_lid == 0) {
+ y[row] = static_cast<T>(result[row]);
+ }
}
+}
+
+template <typename T, int group_size, int bits, bool use_zero_points>
+void qvm_impl_core(
+ const device uint32_t* ws,
+ const device T* scales,
+ const device T* biases,
+ const device uint8_t* zero_points,
+ const device T* x,
+ device T* y,
+ const int in_vec_size,
+ const int out_vec_size,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int num_simdgroups = 2;
+ constexpr int pack_factor = get_pack_factor<bits, 32>();
+ constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>();
+ constexpr int tn = 32 / pack_factor;
+ constexpr int block_size = 32;
+
+ typedef float U;
+ typedef struct {
+ uint8_t wi[tn * bytes_per_pack];
+ } vec_w;
- const device uint8_t* w_row = ((const device uint8_t*)w) + out_col * K * bytes_per_pack / pack_factor;
- const int in_vec_size_g = (K + group_size - 1) / group_size;
- const device T* scales_row = scales + out_col * in_vec_size_g;
- const device uint8_t* zps_row = zero_points + out_col * ((in_vec_size_g + 1) / 2);
- const device T* x_row = x + in_row * K;
- device T* y_row = y + in_row * N + out_col;
+ thread vec_w w_local;
+ thread U result[tn * pack_factor] = {0};
- U result[BN / WN] = {0};
- thread U x_thread[pack_factor];
+ const int out_vec_size_w = out_vec_size * bytes_per_pack / pack_factor;
+ const int out_vec_size_g = out_vec_size / group_size;
+ const int out_col = pack_factor * tn * (tid.y * num_simdgroups + simd_gid);
+
+ if (out_col >= out_vec_size) {
+ return;
+ }
- for (int k = lidx * pack_factor; k < K; k += BK * pack_factor) {
- const int k_pack = k / pack_factor;
- const int remaining = min(pack_factor, K - k);
+ const int out_group = out_col / group_size;
+ const int zp_row_stride = use_zero_points ? ((bits == 4) ? ((out_vec_size_g + 1) / 2) : out_vec_size_g) : 0;
+
+ const device uint8_t* ws_ptr =
+ (const device uint8_t*)ws +
+ out_col * bytes_per_pack / pack_factor +
+ simd_lid * out_vec_size_w;
+ const device T* scales_base = scales;
+ const device T* biases_base = biases;
+ x += tid.x * in_vec_size + simd_lid;
+ y += tid.x * out_vec_size + out_col;
+
+ for (int k_base = 0; k_base < in_vec_size; k_base += block_size) {
+ const int k_index = k_base + simd_lid;
+ const bool active = k_index < in_vec_size;
+
+ U x_local = active ? static_cast<U>(*x) : U(0);
+ U scale = active ? static_cast<U>(scales_base[k_index * out_vec_size_g + out_group]) : U(0);
+ U bias;
- U x_sum = load_vector_safe<T, U, pack_factor, bits>(
- x_row + k, x_thread, remaining);
+ if (use_zero_points && active) {
+ U zp;
+ if (bits == 4) {
+ const device uint8_t* row_ptr = zero_points + k_index * zp_row_stride;
+ const device uint8_t* zp_ptr = row_ptr + (out_group >> 1);
+ uint8_t zp_byte = *zp_ptr;
+ bool high_nibble = (out_group & 1) != 0;
+ zp = static_cast<U>(high_nibble ? ((zp_byte >> 4) & 0x0F) : (zp_byte & 0x0F));
+ } else {
+ const device uint8_t* row_ptr = zero_points + k_index * zp_row_stride;
+ const device uint8_t* zp_ptr = row_ptr + out_group;
+ zp = static_cast<U>(*zp_ptr);
+ }
+ bias = -scale * zp;
+ } else if (active) {
+ bias = static_cast<U>(biases_base[k_index * out_vec_size_g + out_group]);
+ } else {
+ bias = U(0);
+ }
+
+ if (active) {
+ w_local = *((device vec_w*)ws_ptr);
+ }
- for (int n = 0; n < min(bn, N - out_col); n++) {
- const int w_offset = n * K * bytes_per_pack / pack_factor + k_pack * bytes_per_pack;
- const int scale_idx = n * ((K + group_size - 1) / group_size) + k / group_size;
-
- U scale = static_cast<U>(scales_row[scale_idx]);
- uint8_t zp_b = zps_row[k / group_size / 2];
- U bias = static_cast<U>(-scale * static_cast<U>(((k / group_size) & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F)));
-
- result[n] += qdot_safe<U, pack_factor, bits>(
- w_row + w_offset, x_thread, scale, bias, x_sum, remaining);
+ qouter<U, tn * pack_factor, bits>(
+ (thread uint8_t*)&w_local, x_local, scale, bias, result);
+
+ x += block_size;
+ scales += block_size * out_vec_size_g;
+ if (!use_zero_points) {
+ biases += block_size * out_vec_size_g;
}
+ ws_ptr += block_size * out_vec_size_w;
+ }
+
+#pragma clang loop unroll(full)
+ for (int k = 0; k < tn * pack_factor; k++) {
+ result[k] = simd_sum(result[k]);
}
- for (int n = 0; n < min(bn, N - out_col); n++) {
- result[n] = simd_sum(result[n]);
- if (lidx == 0) {
- y_row[n] = static_cast<T>(result[n]);
+ if (simd_lid == 0) {
+#pragma clang loop unroll(full)
+ for (int k = 0; k < tn * pack_factor; k++) {
+ y[k] = static_cast<T>(result[k]);
}
}
}
+template <typename T, int group_size, int bits>
+void qvm_impl_mlx(
+ const device uint32_t* ws,
+ const device T* scales,
+ const device T* biases,
+ const device T* x,
+ device T* y,
+ const int in_vec_size,
+ const int out_vec_size,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ qvm_impl_core<T, group_size, bits, false>(
+ ws, scales, biases, nullptr, x, y, in_vec_size, out_vec_size, tid, simd_gid, simd_lid);
+}
+
+template <typename T, int group_size, int bits>
+void qvm_impl_zeropoint(
+ const device uint32_t* w,
+ const device T* scales,
+ const device uint8_t* zero_points,
+ const device T* x,
+ device T* y,
+ const int in_vec_size,
+ const int out_vec_size,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ qvm_impl_core<T, group_size, bits, true>(
+ w, scales, nullptr, zero_points, x, y, in_vec_size, out_vec_size, tid, simd_gid, simd_lid);
+}
+
+template <typename T, int group_size, int bits>
+void qvm_impl(
+ const device uint32_t* w,
+ const device T* scales,
+ const device uint8_t* zero_points,
+ const device T* biases,
+ const device T* x,
+ device T* y,
+ const constant int& K, // in_vec_size
+ const constant int& N, // out_vec_size
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ if (kUseMlxQuant) {
+ qvm_impl_mlx<T, group_size, bits>(
+ w, scales, biases, x, y, K, N, tid, simd_gid, simd_lid);
+ } else {
+ qvm_impl_zeropoint<T, group_size, bits>(
+ w, scales, zero_points, x, y, K, N, tid, simd_gid, simd_lid);
+ }
+}
+
template <
typename T,
const int group_size,
const int bits,
+ const bool aligned_K,
const int BM = 32,
const int BK = 32,
const int BN = 32>
[[kernel]] void qmm(
const device uint32_t* w [[buffer(0)]],
const device T* scales [[buffer(1)]],
- const device uint8_t* zero_points [[buffer(2)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],
const device T* x [[buffer(3)]],
device T* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -874,7 +1409,7 @@ template <
uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
-
+
(void)lid;
constexpr int BK_padded = (BK + 16 / sizeof(T));
@@ -883,8 +1418,8 @@ template <
threadgroup T Xs[BM * BK_padded];
threadgroup T Ws[BK * BN_padded];
- qmm_impl<T, group_size, bits, BM, BK, BN>(
- w, scales, zero_points, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid);
+ qmm_impl<T, group_size, bits, aligned_K, BM, BK, BN>(
+ w, scales, zero_points, biases, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid);
}
template <
@@ -898,7 +1433,8 @@ template <
[[kernel]] void qmm_transposed(
const device uint32_t* w [[buffer(0)]],
const device T* scales [[buffer(1)]],
- const device uint8_t* zero_points [[buffer(2)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],
const device T* x [[buffer(3)]],
device T* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -908,7 +1444,7 @@ template <
uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
-
+
(void)lid;
constexpr int BK_padded = (BK + 16 / sizeof(T));
@@ -917,14 +1453,15 @@ template <
threadgroup T Ws[BN * BK_padded];
qmm_transposed_impl<T, group_size, bits, aligned_N, BM, BK, BN>(
- w, scales, zero_points, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid);
+ w, scales, zero_points, biases, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid);
}
template <typename T, int group_size, int bits>
[[kernel]] void qmv(
const device uint32_t* w [[buffer(0)]],
const device T* scales [[buffer(1)]],
- const device uint8_t* zero_points [[buffer(2)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],
const device T* x [[buffer(3)]],
device T* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -933,14 +1470,15 @@ template <typename T, int group_size, int bits>
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
- qmv_impl<T, group_size, bits>(w, scales, zero_points, x, y, K, N, tid, simd_gid, simd_lid);
+ qmv_impl<T, group_size, bits>(w, scales, zero_points, biases, x, y, K, N, tid, simd_gid, simd_lid);
}
template <typename T, int group_size, int bits>
[[kernel]] void qvm(
const device uint32_t* w [[buffer(0)]],
const device T* scales [[buffer(1)]],
- const device uint8_t* zero_points [[buffer(2)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],
const device T* x [[buffer(3)]],
device T* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -948,46 +1486,61 @@ template <typename T, int group_size, int bits>
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
-
- qvm_impl<T, group_size, bits>(w, scales, zero_points, x, y, K, N, tid, simd_gid, simd_lid);
+
+ qvm_impl<T, group_size, bits>(
+ w, scales, zero_points, biases, x, y, K, N, tid, simd_gid, simd_lid);
}
-// Group size 32 (F16)
-template [[host_name("qmm_f16_g32_b4")]]
-[[kernel]] void qmm<half, 32, 4>(
+template <typename T, int group_size, int bits>
+[[kernel]] void qmv_fast(
+ const device uint32_t* w [[buffer(0)]],
+ const device T* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device T* x [[buffer(3)]],
+ device T* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ qmv_fast_impl<T, group_size, bits>(w, scales, zero_points, biases, x, y, K, N, tid, simd_gid, simd_lid);
+}
+
+template [[host_name("qmv_f16_g32_b4_fast")]]
+[[kernel]] void qmv_fast<half, 32, 4>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_transposed_f16_g32_b4")]]
-[[kernel]] void qmm_transposed<half, 32, 4, true>(
+template [[host_name("qmv_f16_g64_b4_fast")]]
+[[kernel]] void qmv_fast<half, 64, 4>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmv_f16_g32_b4")]]
-[[kernel]] void qmv<half, 32, 4>(
+template [[host_name("qmv_f16_g128_b4_fast")]]
+[[kernel]] void qmv_fast<half, 128, 4>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -996,111 +1549,110 @@ template [[host_name("qmv_f16_g32_b4")]]
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qvm_f16_g32_b4")]]
-[[kernel]] void qvm<half, 32, 4>(
+template [[host_name("qmv_bf16_g32_b4_fast")]]
+[[kernel]] void qmv_fast<bfloat, 32, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-// Group size 64 (F16)
-template [[host_name("qmm_f16_g64_b4")]]
-[[kernel]] void qmm<half, 64, 4>(
+template [[host_name("qmv_bf16_g64_b4_fast")]]
+[[kernel]] void qmv_fast<bfloat, 64, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_transposed_f16_g64_b4")]]
-[[kernel]] void qmm_transposed<half, 64, 4, true>(
+template [[host_name("qmv_bf16_g128_b4_fast")]]
+[[kernel]] void qmv_fast<bfloat, 128, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmv_f16_g64_b4")]]
-[[kernel]] void qmv<half, 64, 4>(
+template [[host_name("qmv_f32_g32_b4_fast")]]
+[[kernel]] void qmv_fast<float, 32, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qvm_f16_g64_b4")]]
-[[kernel]] void qvm<half, 64, 4>(
+template [[host_name("qmv_f32_g64_b4_fast")]]
+[[kernel]] void qmv_fast<float, 64, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_f16_g128_b4")]]
-[[kernel]] void qmm<half, 128, 4>(
+template [[host_name("qmv_f32_g128_b4_fast")]]
+[[kernel]] void qmv_fast<float, 128, 4>(
const device uint32_t* w [[buffer(0)]],
- const device half* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device half* x [[buffer(3)]],
- device half* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_transposed_f16_g128_b4")]]
-[[kernel]] void qmm_transposed<half, 128, 4, true>(
+template [[host_name("qmv_f16_g32_b8_fast")]]
+[[kernel]] void qmv_fast<half, 32, 8>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmv_f16_g128_b4")]]
-[[kernel]] void qmv<half, 128, 4>(
+template [[host_name("qmv_f16_g64_b8_fast")]]
+[[kernel]] void qmv_fast<half, 64, 8>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1109,11 +1661,12 @@ template [[host_name("qmv_f16_g128_b4")]]
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qvm_f16_g128_b4")]]
-[[kernel]] void qvm<half, 128, 4>(
+template [[host_name("qmv_f16_g128_b8_fast")]]
+[[kernel]] void qmv_fast<half, 128, 8>(
const device uint32_t* w [[buffer(0)]],
const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
const device half* x [[buffer(3)]],
device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1122,42 +1675,40 @@ template [[host_name("qvm_f16_g128_b4")]]
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-// Group size 32 (BF16)
-template [[host_name("qmm_bf16_g32_b4")]]
-[[kernel]] void qmm<bfloat, 32, 4>(
+template [[host_name("qmv_bf16_g32_b8_fast")]]
+[[kernel]] void qmv_fast<bfloat, 32, 8>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_transposed_bf16_g32_b4")]]
-[[kernel]] void qmm_transposed<bfloat, 32, 4, true>(
+template [[host_name("qmv_bf16_g64_b8_fast")]]
+[[kernel]] void qmv_fast<bfloat, 64, 8>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmv_bf16_g32_b4")]]
-[[kernel]] void qmv<bfloat, 32, 4>(
+template [[host_name("qmv_bf16_g128_b8_fast")]]
+[[kernel]] void qmv_fast<bfloat, 128, 8>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1166,67 +1717,1528 @@ template [[host_name("qmv_bf16_g32_b4")]]
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qvm_bf16_g32_b4")]]
-[[kernel]] void qvm<bfloat, 32, 4>(
+template [[host_name("qmv_f32_g32_b8_fast")]]
+[[kernel]] void qmv_fast<float, 32, 8>(
const device uint32_t* w [[buffer(0)]],
- const device bfloat* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device bfloat* x [[buffer(3)]],
- device bfloat* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
uint3 tid [[threadgroup_position_in_grid]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_bf16_g64_b4")]]
-[[kernel]] void qmm<bfloat, 64, 4>(
+template [[host_name("qmv_f32_g64_b8_fast")]]
+[[kernel]] void qmv_fast<float, 64, 8>(
const device uint32_t* w [[buffer(0)]],
- const device bfloat* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device bfloat* x [[buffer(3)]],
- device bfloat* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmm_transposed_bf16_g64_b4")]]
-[[kernel]] void qmm_transposed<bfloat, 64, 4, true>(
+template [[host_name("qmv_f32_g128_b8_fast")]]
+[[kernel]] void qmv_fast<float, 128, 8>(
const device uint32_t* w [[buffer(0)]],
- const device bfloat* scales [[buffer(1)]],
+ const device float* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device bfloat* x [[buffer(3)]],
- device bfloat* y [[buffer(4)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
- const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
- uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qmv_bf16_g64_b4")]]
-[[kernel]] void qmv<bfloat, 64, 4>(
+// Group size 32 (F16)
+template [[host_name("qmm_f16_g32_b4")]]
+[[kernel]] void qmm<half, 32, 4, false>(
const device uint32_t* w [[buffer(0)]],
- const device bfloat* scales [[buffer(1)]],
+ const device half* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
- const device bfloat* x [[buffer(3)]],
- device bfloat* y [[buffer(4)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]);
-template [[host_name("qvm_bf16_g64_b4")]]
-[[kernel]] void qvm<bfloat, 64, 4>(
+template [[host_name("qmm_transposed_f16_g32_b4")]]
+[[kernel]] void qmm_transposed<half, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g32_b4_unaligned")]]
+[[kernel]] void qmm_transposed<half, 32, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g32_b4_alignedk")]]
+[[kernel]] void qmm<half, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g32_b4")]]
+[[kernel]] void qmv<half, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g32_b4")]]
+[[kernel]] void qvm<half, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 32 (F16) - 8 bit
+template [[host_name("qmm_f16_g32_b8")]]
+[[kernel]] void qmm<half, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g32_b8")]]
+[[kernel]] void qmm_transposed<half, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g32_b8_unaligned")]]
+[[kernel]] void qmm_transposed<half, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g32_b8_alignedk")]]
+[[kernel]] void qmm<half, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g32_b8")]]
+[[kernel]] void qmv<half, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g32_b8")]]
+[[kernel]] void qvm<half, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (F16)
+template [[host_name("qmm_f16_g64_b4")]]
+[[kernel]] void qmm<half, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g64_b4_alignedk")]]
+[[kernel]] void qmm<half, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g64_b4")]]
+[[kernel]] void qmm_transposed<half, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g64_b4_unaligned")]]
+[[kernel]] void qmm_transposed<half, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g64_b4")]]
+[[kernel]] void qmv<half, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g64_b4")]]
+[[kernel]] void qvm<half, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (F16) - 8 bit
+template [[host_name("qmm_f16_g64_b8")]]
+[[kernel]] void qmm<half, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g64_b8_alignedk")]]
+[[kernel]] void qmm<half, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g64_b8")]]
+[[kernel]] void qmm_transposed<half, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g64_b8_unaligned")]]
+[[kernel]] void qmm_transposed<half, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g64_b8")]]
+[[kernel]] void qmv<half, 64, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g64_b8")]]
+[[kernel]] void qvm<half, 64, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 128 (F16)
+template [[host_name("qmm_f16_g128_b4")]]
+[[kernel]] void qmm<half, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g128_b4_alignedk")]]
+[[kernel]] void qmm<half, 128, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g128_b4")]]
+[[kernel]] void qmm_transposed<half, 128, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g128_b4_unaligned")]]
+[[kernel]] void qmm_transposed<half, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g128_b4")]]
+[[kernel]] void qmv<half, 128, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g128_b4")]]
+[[kernel]] void qvm<half, 128, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 128 (F16) - 8 bit
+template [[host_name("qmm_f16_g128_b8")]]
+[[kernel]] void qmm<half, 128, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f16_g128_b8_alignedk")]]
+[[kernel]] void qmm<half, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g128_b8")]]
+[[kernel]] void qmm_transposed<half, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f16_g128_b8_unaligned")]]
+[[kernel]] void qmm_transposed<half, 128, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f16_g128_b8")]]
+[[kernel]] void qmv<half, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device half* biases [[buffer(2)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f16_g128_b8")]]
+[[kernel]] void qvm<half, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device half* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device half* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device half* x [[buffer(3)]],
+ device half* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 32 (F32)
+template [[host_name("qmm_f32_g32_b4")]]
+[[kernel]] void qmm<float, 32, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g32_b4")]]
+[[kernel]] void qmm_transposed<float, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g32_b4_unaligned")]]
+[[kernel]] void qmm_transposed<float, 32, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g32_b4_alignedk")]]
+[[kernel]] void qmm<float, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g32_b4")]]
+[[kernel]] void qmv<float, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g32_b4")]]
+[[kernel]] void qvm<float, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 32 (F32) - 8 bit
+template [[host_name("qmm_f32_g32_b8")]]
+[[kernel]] void qmm<float, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g32_b8")]]
+[[kernel]] void qmm_transposed<float, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g32_b8_unaligned")]]
+[[kernel]] void qmm_transposed<float, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g32_b8_alignedk")]]
+[[kernel]] void qmm<float, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g32_b8")]]
+[[kernel]] void qmv<float, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g32_b8")]]
+[[kernel]] void qvm<float, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (F32)
+template [[host_name("qmm_f32_g64_b4")]]
+[[kernel]] void qmm<float, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g64_b4_alignedk")]]
+[[kernel]] void qmm<float, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g64_b4")]]
+[[kernel]] void qmm_transposed<float, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g64_b4_unaligned")]]
+[[kernel]] void qmm_transposed<float, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g64_b4")]]
+[[kernel]] void qmv<float, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g64_b4")]]
+[[kernel]] void qvm<float, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (F32) - 8 bit
+template [[host_name("qmm_f32_g64_b8")]]
+[[kernel]] void qmm<float, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g64_b8_alignedk")]]
+[[kernel]] void qmm<float, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g64_b8")]]
+[[kernel]] void qmm_transposed<float, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g64_b8_unaligned")]]
+[[kernel]] void qmm_transposed<float, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g64_b8")]]
+[[kernel]] void qmv<float, 64, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g64_b8")]]
+[[kernel]] void qvm<float, 64, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 128 (F32)
+template [[host_name("qmm_f32_g128_b4")]]
+[[kernel]] void qmm<float, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g128_b4_alignedk")]]
+[[kernel]] void qmm<float, 128, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g128_b4")]]
+[[kernel]] void qmm_transposed<float, 128, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g128_b4_unaligned")]]
+[[kernel]] void qmm_transposed<float, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g128_b4")]]
+[[kernel]] void qmv<float, 128, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g128_b4")]]
+[[kernel]] void qvm<float, 128, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 128 (F32) - 8 bit
+template [[host_name("qmm_f32_g128_b8")]]
+[[kernel]] void qmm<float, 128, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_f32_g128_b8_alignedk")]]
+[[kernel]] void qmm<float, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g128_b8")]]
+[[kernel]] void qmm_transposed<float, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_f32_g128_b8_unaligned")]]
+[[kernel]] void qmm_transposed<float, 128, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_f32_g128_b8")]]
+[[kernel]] void qmv<float, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device float* biases [[buffer(2)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_f32_g128_b8")]]
+[[kernel]] void qvm<float, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device float* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device float* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device float* x [[buffer(3)]],
+ device float* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 32 (BF16)
+template [[host_name("qmm_bf16_g32_b4")]]
+[[kernel]] void qmm<bfloat, 32, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g32_b4_alignedk")]]
+[[kernel]] void qmm<bfloat, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g32_b4")]]
+[[kernel]] void qmm_transposed<bfloat, 32, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g32_b4_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 32, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_bf16_g32_b4")]]
+[[kernel]] void qmv<bfloat, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_bf16_g32_b4")]]
+[[kernel]] void qvm<bfloat, 32, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 32 (BF16) - 8 bit
+template [[host_name("qmm_bf16_g32_b8")]]
+[[kernel]] void qmm<bfloat, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g32_b8_alignedk")]]
+[[kernel]] void qmm<bfloat, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g32_b8")]]
+[[kernel]] void qmm_transposed<bfloat, 32, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g32_b8_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 32, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_bf16_g32_b8")]]
+[[kernel]] void qmv<bfloat, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_bf16_g32_b8")]]
+[[kernel]] void qvm<bfloat, 32, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (BF16)
+template [[host_name("qmm_bf16_g64_b4")]]
+[[kernel]] void qmm<bfloat, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g64_b4_alignedk")]]
+[[kernel]] void qmm<bfloat, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g64_b4")]]
+[[kernel]] void qmm_transposed<bfloat, 64, 4, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g64_b4_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 64, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_bf16_g64_b4")]]
+[[kernel]] void qmv<bfloat, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_bf16_g64_b4")]]
+[[kernel]] void qvm<bfloat, 64, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 64 (BF16) - 8 bit
+template [[host_name("qmm_bf16_g64_b8")]]
+[[kernel]] void qmm<bfloat, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g64_b8_alignedk")]]
+[[kernel]] void qmm<bfloat, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g64_b8")]]
+[[kernel]] void qmm_transposed<bfloat, 64, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g64_b8_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 64, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_bf16_g64_b8")]]
+[[kernel]] void qmv<bfloat, 64, 8>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_bf16_g64_b8")]]
+[[kernel]] void qvm<bfloat, 64, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1237,10 +3249,27 @@ template [[host_name("qvm_bf16_g64_b4")]]
// Group size 128 (BF16)
template [[host_name("qmm_bf16_g128_b4")]]
-[[kernel]] void qmm<bfloat, 128, 4>(
+[[kernel]] void qmm<bfloat, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g128_b4_alignedk")]]
+[[kernel]] void qmm<bfloat, 128, 4, true>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1256,6 +3285,23 @@ template [[host_name("qmm_transposed_bf16_g128_b4")]]
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g128_b4_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 4, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1271,6 +3317,7 @@ template [[host_name("qmv_bf16_g128_b4")]]
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
@@ -1281,13 +3328,156 @@ template [[host_name("qmv_bf16_g128_b4")]]
template [[host_name("qvm_bf16_g128_b4")]]
[[kernel]] void qvm<bfloat, 128, 4>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+// Group size 128 (BF16) - 8 bit
+template [[host_name("qmm_bf16_g128_b8")]]
+[[kernel]] void qmm<bfloat, 128, 8, false>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_bf16_g128_b8_alignedk")]]
+[[kernel]] void qmm<bfloat, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g128_b8")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 8, true>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g128_b8_unaligned")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 8, false>(
const device uint32_t* w [[buffer(0)]],
const device bfloat* scales [[buffer(1)]],
const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
const device bfloat* x [[buffer(3)]],
device bfloat* y [[buffer(4)]],
const constant int& K [[buffer(5)]],
const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmv_bf16_g128_b8")]]
+[[kernel]] void qmv<bfloat, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qvm_bf16_g128_b8")]]
+[[kernel]] void qvm<bfloat, 128, 8>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],
+ const device bfloat* biases [[buffer(2), function_constant(kUseMlxQuant)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g128_b4_64x64")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 4, true, 64, 32, 64>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+template [[host_name("qmm_transposed_bf16_g128_b4_64x128")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 4, true, 64, 32, 128>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]);
+
+
+template [[host_name("qmm_transposed_bf16_g128_b4_128x64")]]
+[[kernel]] void qmm_transposed<bfloat, 128, 4, true, 128, 32, 64>(
+ const device uint32_t* w [[buffer(0)]],
+ const device bfloat* scales [[buffer(1)]],
+ const device uint8_t* zero_points [[buffer(2)]],
+ const device bfloat* biases [[buffer(2)]],
+ const device bfloat* x [[buffer(3)]],
+ device bfloat* y [[buffer(4)]],
+ const constant int& K [[buffer(5)]],
+ const constant int& N [[buffer(6)]],
+ const constant int& M [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
uint simd_gid [[simdgroup_index_in_threadgroup]],
- uint simd_lid [[thread_index_in_simdgroup]]);
\ No newline at end of file
+ uint simd_lid [[thread_index_in_simdgroup]]);
diff --git a/crates/uzu/src/backends/metal/kernel/sampling/mod.rs b/crates/uzu/src/backends/metal/kernel/sampling/mod.rs
index 74639522d..2ef7ff152 100644
--- a/crates/uzu/src/backends/metal/kernel/sampling/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/sampling/mod.rs
@@ -653,7 +653,7 @@ impl EncodableWithState for SamplingKernelEncodable {
use crate::Array;
logits.shape()
};
- let batch_size = logits_shape[0];
+ let batch_size = state.active_suffix_length();
let vocab_size = logits_shape[1];
let seeds_binding = state.arrays(&[
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.metal b/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.metal
new file mode 100644
index 000000000..dc477a170
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.metal
@@ -0,0 +1,286 @@
+#include <metal_stdlib>
+#include "../definitions.metal"
+
+using namespace metal;
+
+constant int activation_type [[function_constant(0)]];
+
+constant int ACTIVATION_IDENTITY = 0;
+constant int ACTIVATION_SILU = 1;
+constant int ACTIVATION_GELU = 2;
+
+constant uint CONV_SCAN_THREADS = 32u;
+
+template <typename T>
+inline T apply_silu(T x) {
+ float xf = float(x);
+ float y = 1.0f / (1.0f + fast::exp(-fabs(xf)));
+ float out = (xf < 0.0f) ? (1.0f - y) * xf : y * xf;
+ return static_cast<T>(out);
+}
+
+template <typename T>
+inline T apply_gelu(T x) {
+ float xf = float(x);
+ return static_cast<T>(0.5f * xf * (1.0f + fast::tanh(0.797885f * (xf + 0.044715f * xf * xf * xf))));
+}
+
+template <typename T>
+inline T apply_activation_fn(T x, int activation_type) {
+ if (activation_type == ACTIVATION_SILU) {
+ return apply_silu(x);
+ } else if (activation_type == ACTIVATION_GELU) {
+ return apply_gelu(x);
+ } else {
+ return x; // Identity
+ }
+}
+
+template <typename T>
+kernel void conv1d_pack_prefix_kernel(
+ device const T* state_in [[ buffer(0) ]],
+ device const T* x [[ buffer(1) ]],
+ device T* padded [[ buffer(2) ]],
+ constant const size_t& state_stride [[ buffer(3) ]],
+ constant const size_t& row_stride [[ buffer(4) ]],
+ constant const size_t& suffix_len [[ buffer(5) ]],
+ constant const uint& num_channels [[ buffer(6) ]],
+ uint2 grid_idx [[ thread_position_in_grid ]]
+) {
+ const uint channel_idx = grid_idx.x;
+ const uint row_idx = grid_idx.y;
+ const size_t padded_rows = state_stride + suffix_len;
+ if (channel_idx >= num_channels || row_idx >= padded_rows) {
+ return;
+ }
+ const size_t padded_index =
+ size_t(row_idx) * row_stride + size_t(channel_idx);
+ if (row_idx < state_stride) {
+ const size_t state_index =
+ size_t(channel_idx) * state_stride + size_t(row_idx);
+ padded[padded_index] = state_in[state_index];
+ } else {
+ const size_t token = row_idx - state_stride;
+ const size_t x_index =
+ size_t(token) * row_stride + size_t(channel_idx);
+ padded[padded_index] = x[x_index];
+ }
+}
+
+template <typename T>
+kernel void conv1d_scan_kernel(
+ device const T* padded [[ buffer(0) ]], // (prefix+suffix, channels)
+ device const T* w [[ buffer(1) ]], // (channels, kernel)
+ device const T* b [[ buffer(2) ]], // optional (channels)
+ device T* x_out [[ buffer(3) ]], // (suffix, inner_dim)
+ device T* b_out [[ buffer(4) ]], // (suffix, proj_dim)
+ device T* c_out [[ buffer(5) ]], // (suffix, proj_dim)
+ device T* state_out [[ buffer(6) ]], // (channels, kernel-1)
+ constant const size_t& suffix_len [[ buffer(7) ]],
+ constant const int& kernel_size [[ buffer(8) ]],
+ constant const size_t& row_stride [[ buffer(9) ]],
+ constant const size_t& state_stride [[ buffer(10) ]],
+ constant const uint& num_channels [[ buffer(11) ]],
+ constant const uint& inner_dim [[ buffer(12) ]],
+ constant const uint& proj_dim [[ buffer(13) ]],
+ uint3 grid_idx [[ thread_position_in_grid ]]
+) {
+ const int kernel_value = kernel_size;
+ if (kernel_value <= 0) {
+ return;
+ }
+
+ const int tap_count = max(kernel_value - 1, 0);
+ const size_t work_len = suffix_len + size_t(tap_count);
+
+ const uint token_idx = grid_idx.x;
+ const uint channel_idx = grid_idx.y;
+ if (channel_idx >= num_channels || token_idx >= work_len) {
+ return;
+ }
+
+ const size_t state_offset = size_t(channel_idx) * state_stride;
+ const size_t weight_offset = size_t(channel_idx) * size_t(kernel_value);
+ const device T* w_row = w + weight_offset;
+ const bool has_bias = b != nullptr;
+
+ if (token_idx < suffix_len) {
+ float acc = has_bias ? float(b[channel_idx]) : 0.0f;
+ for (int tap = 0; tap < kernel_value; ++tap) {
+ const size_t padded_idx = size_t(token_idx) + size_t(tap);
+ float sample = 0.0f;
+ const size_t padded_index =
+ size_t(padded_idx) * row_stride + channel_idx;
+ sample = float(padded[padded_index]);
+ acc += float(w_row[tap]) * sample;
+ }
+
+ const T activated = apply_activation_fn(static_cast<T>(acc), activation_type);
+ if (channel_idx < inner_dim) {
+ const size_t dst = size_t(token_idx) * inner_dim + channel_idx;
+ x_out[dst] = activated;
+ } else if (channel_idx < inner_dim + proj_dim) {
+ const size_t dst = size_t(token_idx) * proj_dim + (channel_idx - inner_dim);
+ b_out[dst] = activated;
+ } else if (channel_idx < inner_dim + 2 * proj_dim) {
+ const size_t dst = size_t(token_idx) * proj_dim + (channel_idx - inner_dim - proj_dim);
+ c_out[dst] = activated;
+ }
+ } else if (tap_count > 0) {
+ const size_t tap = size_t(token_idx - suffix_len);
+ if (tap >= size_t(tap_count)) {
+ return;
+ }
+ const size_t padded_index =
+ size_t(token_idx) * row_stride + channel_idx;
+ const float sample = float(padded[padded_index]);
+ state_out[state_offset + tap] = static_cast<T>(sample);
+ }
+}
+
+template <typename T>
+kernel void conv1d_decode_kernel(
+ device const T* x [[ buffer(0) ]],
+ device const T* w [[ buffer(1) ]],
+ device const T* b [[ buffer(2) ]],
+ device const T* state [[ buffer(3) ]],
+ device T* x_out [[ buffer(4) ]],
+ device T* b_out [[ buffer(5) ]],
+ device T* c_out [[ buffer(6) ]],
+ device T* next_state [[ buffer(7) ]],
+ constant const int& kernel_size [[ buffer(8) ]],
+ constant const size_t& row_stride [[ buffer(9) ]],
+ constant const size_t& state_stride [[ buffer(10) ]],
+ constant const uint& num_channels [[ buffer(11) ]],
+ constant const size_t& suffix_len [[ buffer(12) ]],
+ constant const uint& inner_dim [[ buffer(13) ]],
+ constant const uint& proj_dim [[ buffer(14) ]],
+ uint2 grid_idx [[ thread_position_in_grid ]]
+) {
+ const int kernel_value = kernel_size;
+ if (kernel_value <= 0) {
+ return;
+ }
+
+ const uint token_idx = grid_idx.x;
+ const uint channel_idx = grid_idx.y;
+ if (channel_idx >= num_channels || token_idx >= suffix_len) {
+ return;
+ }
+
+ const size_t x_idx =
+ size_t(token_idx) * row_stride + size_t(channel_idx);
+ const size_t state_offset =
+ size_t(channel_idx) * state_stride;
+ const device T* w_row =
+ w + size_t(channel_idx) * size_t(kernel_value);
+ const bool has_bias = b != nullptr;
+
+ float acc = has_bias ? float(b[channel_idx]) : 0.0f;
+ const int state_taps = max(kernel_value - 1, 0);
+ for (int tap = 0; tap < state_taps; ++tap) {
+ const size_t state_index = state_offset + size_t(tap);
+ const float sample = float(state[state_index]);
+ acc += float(w_row[tap]) * sample;
+ }
+
+ const float current = float(x[x_idx]);
+ const int current_tap_index = state_taps;
+ if (current_tap_index < kernel_value) {
+ acc += float(w_row[current_tap_index]) * current;
+ }
+
+ const T activated = apply_activation_fn(static_cast<T>(acc), activation_type);
+ if (channel_idx < inner_dim) {
+ const size_t dst = size_t(token_idx) * inner_dim + channel_idx;
+ x_out[dst] = activated;
+ } else if (channel_idx < inner_dim + proj_dim) {
+ const size_t dst = size_t(token_idx) * proj_dim + (channel_idx - inner_dim);
+ b_out[dst] = activated;
+ } else if (channel_idx < inner_dim + 2 * proj_dim) {
+ const size_t dst = size_t(token_idx) * proj_dim + (channel_idx - inner_dim - proj_dim);
+ c_out[dst] = activated;
+ }
+
+ if (state_taps == 0) {
+ return;
+ }
+
+ for (int tap = 0; tap < state_taps - 1; ++tap) {
+ const size_t dst_index = state_offset + size_t(tap);
+ const size_t src_index = state_offset + size_t(tap + 1);
+ next_state[dst_index] = state[src_index];
+ }
+
+ const size_t tail_index = state_offset + size_t(state_taps - 1);
+ next_state[tail_index] = static_cast<T>(current);
+}
+
+#define instantiate_conv1d_pack_prefix_kernel(type_name, type) \
+ template [[host_name("conv1d_pack_prefix_kernel_" #type_name)]] \
+ kernel void conv1d_pack_prefix_kernel<type>( \
+ device const type* state_in [[ buffer(0) ]], \
+ device const type* x [[ buffer(1) ]], \
+ device type* padded [[ buffer(2) ]], \
+ constant const size_t& state_stride [[ buffer(3) ]], \
+ constant const size_t& row_stride [[ buffer(4) ]], \
+ constant const size_t& suffix_len [[ buffer(5) ]], \
+ constant const uint& num_channels [[ buffer(6) ]], \
+ uint2 grid_idx [[ thread_position_in_grid ]] \
+ );
+
+#define instantiate_conv1d_scan_kernel(type_name, type) \
+ template [[host_name("conv1d_scan_kernel_" #type_name)]] \
+ kernel void conv1d_scan_kernel<type>( \
+ device const type* padded [[ buffer(0) ]], \
+ device const type* w [[ buffer(1) ]], \
+ device const type* b [[ buffer(2) ]], \
+ device type* x_out [[ buffer(3) ]], \
+ device type* b_out [[ buffer(4) ]], \
+ device type* c_out [[ buffer(5) ]], \
+ device type* state_out [[ buffer(6) ]], \
+ constant const size_t& suffix_len [[ buffer(7) ]], \
+ constant const int& kernel_size [[ buffer(8) ]], \
+ constant const size_t& row_stride [[ buffer(9) ]], \
+ constant const size_t& state_stride [[ buffer(10) ]], \
+ constant const uint& num_channels [[ buffer(11) ]], \
+ constant const uint& inner_dim [[ buffer(12) ]], \
+ constant const uint& proj_dim [[ buffer(13) ]], \
+ uint3 grid_idx [[ thread_position_in_grid ]] \
+ );
+
+instantiate_conv1d_pack_prefix_kernel(float, float);
+instantiate_conv1d_pack_prefix_kernel(bfloat, bfloat);
+instantiate_conv1d_pack_prefix_kernel(half, half);
+
+instantiate_conv1d_scan_kernel(float, float);
+instantiate_conv1d_scan_kernel(bfloat, bfloat);
+instantiate_conv1d_scan_kernel(half, half);
+
+#define instantiate_conv1d_decode_kernel(type_name, type) \
+ template [[host_name("conv1d_decode_kernel_" #type_name)]] \
+ kernel void conv1d_decode_kernel<type>( \
+ device const type* x [[ buffer(0) ]], \
+ device const type* w [[ buffer(1) ]], \
+ device const type* b [[ buffer(2) ]], \
+ device const type* state [[ buffer(3) ]], \
+ device type* x_out [[ buffer(4) ]], \
+ device type* b_out [[ buffer(5) ]], \
+ device type* c_out [[ buffer(6) ]], \
+ device type* next_state [[ buffer(7) ]], \
+ constant const int& kernel_size [[ buffer(8) ]], \
+ constant const size_t& row_stride [[ buffer(9) ]], \
+ constant const size_t& state_stride [[ buffer(10) ]], \
+ constant const uint& num_channels [[ buffer(11) ]], \
+ constant const size_t& suffix_len [[ buffer(12) ]], \
+ constant const uint& inner_dim [[ buffer(13) ]], \
+ constant const uint& proj_dim [[ buffer(14) ]], \
+ uint2 grid_idx [[ thread_position_in_grid ]] \
+ );
+
+#undef instantiate_conv1d_pack_prefix_kernel
+#undef instantiate_conv1d_scan_kernel
+instantiate_conv1d_decode_kernel(float, float);
+instantiate_conv1d_decode_kernel(bfloat, bfloat);
+instantiate_conv1d_decode_kernel(half, half);
+#undef instantiate_conv1d_decode_kernel
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.rs b/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.rs
new file mode 100644
index 000000000..45cdd7e1d
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/conv1d_scan.rs
@@ -0,0 +1,323 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, FunctionConstantValues,
+ MTLDataType, MTLSize,
+};
+
+use super::{SSMKernelError, fn_suffix};
+use crate::{
+ backends::metal::{KernelDataType, MTLContext},
+ config::Activation,
+};
+
+const CONV1D_SCAN_THREADGROUP_SIZE: u64 = 32;
+
+const ACTIVATION_IDENTITY: i32 = 0;
+const ACTIVATION_SILU: i32 = 1;
+const ACTIVATION_GELU: i32 = 2;
+
+fn activation_to_int(activation: &Activation) -> i32 {
+ match activation {
+ Activation::Identity => ACTIVATION_IDENTITY,
+ Activation::SiLU {
+ ..
+ } => ACTIVATION_SILU,
+ Activation::Gelu => ACTIVATION_GELU,
+ }
+}
+
+fn make_function_constants(activation: &Activation) -> FunctionConstantValues {
+ let function_constants = FunctionConstantValues::new();
+ let activation_type = activation_to_int(activation);
+
+ function_constants.set_constant_value_at_index(
+ &activation_type as *const i32 as *const std::ffi::c_void,
+ MTLDataType::Int,
+ 0,
+ );
+
+ function_constants
+}
+
+pub struct Conv1dScanKernel {
+ pipeline: MTLComputePipelineState,
+ pack_pipeline: MTLComputePipelineState,
+ decode_pipeline: MTLComputePipelineState,
+}
+
+pub struct Conv1dScanArguments<'a> {
+ pub padded: &'a MTLBuffer, // buffer(0) [prefix+suffix, channels]
+ pub w: &'a MTLBuffer, // buffer(1) [channels, kernel]
+ pub b: Option<&'a MTLBuffer>, // buffer(2) [channels]
+ pub x_out: &'a MTLBuffer, // buffer(3) [suffix, inner_dim]
+ pub b_out: &'a MTLBuffer, // buffer(4) [suffix, proj_dim]
+ pub c_out: &'a MTLBuffer, // buffer(5) [suffix, proj_dim]
+ pub state_out: &'a MTLBuffer, // buffer(6) [channels, kernel-1]
+ pub suffix_len: usize,
+ pub kernel_size: i32,
+ pub row_stride: usize,
+ pub state_stride: usize,
+ pub channels: usize,
+ pub inner_dim: usize,
+ pub proj_dim: usize,
+}
+
+pub struct Conv1dPackArguments<'a> {
+ pub state_in: &'a MTLBuffer,
+ pub x: &'a MTLBuffer,
+ pub padded: &'a MTLBuffer,
+ pub state_stride: usize,
+ pub row_stride: usize,
+ pub suffix_len: usize,
+ pub channels: usize,
+}
+
+pub struct Conv1dDecodeArguments<'a> {
+ pub x: &'a MTLBuffer,
+ pub w: &'a MTLBuffer,
+ pub b: Option<&'a MTLBuffer>,
+ pub state: &'a MTLBuffer,
+ pub x_out: &'a MTLBuffer,
+ pub b_out: &'a MTLBuffer,
+ pub c_out: &'a MTLBuffer,
+ pub next_state: &'a MTLBuffer,
+ pub suffix_len: usize,
+ pub kernel_size: i32,
+ pub row_stride: usize,
+ pub state_stride: usize,
+ pub channels: usize,
+ pub inner_dim: usize,
+ pub proj_dim: usize,
+}
+
+impl Conv1dScanKernel {
+ pub fn new(
+ context: &MTLContext,
+ data_type: KernelDataType,
+ activation: &Activation,
+ ) -> Result<Self, SSMKernelError> {
+ let fn_name = format!("conv1d_scan_kernel_{}", fn_suffix(data_type));
+ let pack_name =
+ format!("conv1d_pack_prefix_kernel_{}", fn_suffix(data_type));
+ let decode_name =
+ format!("conv1d_decode_kernel_{}", fn_suffix(data_type));
+ let function_constants = make_function_constants(activation);
+ let pipeline = context
+ .compute_pipeline_state(&fn_name, Some(&function_constants))
+ .map_err(SSMKernelError::MetalError)?;
+ let pack_pipeline = context
+ .compute_pipeline_state(&pack_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ let decode_pipeline = context
+ .compute_pipeline_state(&decode_name, Some(&function_constants))
+ .map_err(SSMKernelError::MetalError)?;
+ Ok(Self {
+ pipeline,
+ pack_pipeline,
+ decode_pipeline,
+ })
+ }
+
+ pub fn encode_pack(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: Conv1dPackArguments,
+ ) -> Result<(), SSMKernelError> {
+ if args.channels == 0 || args.state_stride == 0 {
+ return Ok(());
+ }
+
+ compute_encoder.set_compute_pipeline_state(&self.pack_pipeline);
+ compute_encoder.set_buffer(0, Some(args.state_in), 0);
+ compute_encoder.set_buffer(1, Some(args.x), 0);
+ compute_encoder.set_buffer(2, Some(args.padded), 0);
+ compute_encoder.set_bytes(
+ 3,
+ size_of::<usize>() as u64,
+ &args.state_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 4,
+ size_of::<usize>() as u64,
+ &args.row_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 5,
+ size_of::<usize>() as u64,
+ &args.suffix_len as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &(args.channels as u32) as *const u32 as *const _,
+ );
+
+ let threads_per_threadgroup = MTLSize {
+ width: CONV1D_SCAN_THREADGROUP_SIZE,
+ height: 1,
+ depth: 1,
+ };
+ let padded_rows = args.state_stride + args.suffix_len;
+ let total_threads = MTLSize {
+ width: args.channels as u64,
+ height: padded_rows as u64,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+
+ pub fn encode_decode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: Conv1dDecodeArguments,
+ ) -> Result<(), SSMKernelError> {
+ if args.channels == 0 || args.suffix_len == 0 || args.kernel_size <= 0 {
+ return Ok(());
+ }
+
+ compute_encoder.set_compute_pipeline_state(&self.decode_pipeline);
+ compute_encoder.set_buffer(0, Some(args.x), 0);
+ compute_encoder.set_buffer(1, Some(args.w), 0);
+ if let Some(bias) = args.b {
+ compute_encoder.set_buffer(2, Some(bias), 0);
+ } else {
+ compute_encoder.set_buffer(2, None, 0);
+ }
+ compute_encoder.set_buffer(3, Some(args.state), 0);
+ compute_encoder.set_buffer(4, Some(args.x_out), 0);
+ compute_encoder.set_buffer(5, Some(args.b_out), 0);
+ compute_encoder.set_buffer(6, Some(args.c_out), 0);
+ compute_encoder.set_buffer(7, Some(args.next_state), 0);
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<i32>() as u64,
+ &args.kernel_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<usize>() as u64,
+ &args.row_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<usize>() as u64,
+ &args.state_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ size_of::<u32>() as u64,
+ &(args.channels as u32) as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 12,
+ size_of::<usize>() as u64,
+ &args.suffix_len as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 13,
+ size_of::<u32>() as u64,
+ &(args.inner_dim as u32) as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 14,
+ size_of::<u32>() as u64,
+ &(args.proj_dim as u32) as *const u32 as *const _,
+ );
+
+ let threads_per_threadgroup = MTLSize {
+ width: CONV1D_SCAN_THREADGROUP_SIZE,
+ height: 1,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: args.suffix_len as u64,
+ height: args.channels as u64,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+
+ pub fn encode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: Conv1dScanArguments,
+ ) -> Result<(), SSMKernelError> {
+ if args.channels == 0 || args.suffix_len == 0 || args.kernel_size <= 0 {
+ return Ok(());
+ }
+
+ compute_encoder.set_compute_pipeline_state(&self.pipeline);
+
+ compute_encoder.set_buffer(0, Some(args.padded), 0);
+ compute_encoder.set_buffer(1, Some(args.w), 0);
+ if let Some(bias) = args.b {
+ compute_encoder.set_buffer(2, Some(bias), 0);
+ } else {
+ compute_encoder.set_buffer(2, None, 0);
+ }
+ compute_encoder.set_buffer(3, Some(args.x_out), 0);
+ compute_encoder.set_buffer(4, Some(args.b_out), 0);
+ compute_encoder.set_buffer(5, Some(args.c_out), 0);
+ compute_encoder.set_buffer(6, Some(args.state_out), 0);
+
+ compute_encoder.set_bytes(
+ 7,
+ size_of::<usize>() as u64,
+ &args.suffix_len as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<i32>() as u64,
+ &args.kernel_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<usize>() as u64,
+ &args.row_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<usize>() as u64,
+ &args.state_stride as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ size_of::<u32>() as u64,
+ &(args.channels as u32) as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 12,
+ size_of::<u32>() as u64,
+ &(args.inner_dim as u32) as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 13,
+ size_of::<u32>() as u64,
+ &(args.proj_dim as u32) as *const u32 as *const _,
+ );
+
+ let suffix = args.suffix_len as u64;
+ let tap_count = args.kernel_size.saturating_sub(1) as u64;
+ let work_len = suffix + tap_count;
+ let channels = args.channels as u64;
+ let threads_per_threadgroup = MTLSize {
+ width: CONV1D_SCAN_THREADGROUP_SIZE,
+ height: 1,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: work_len,
+ height: channels,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/mamba.rs b/crates/uzu/src/backends/metal/kernel/ssm/mamba.rs
new file mode 100644
index 000000000..5fc14fa75
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/mamba.rs
@@ -0,0 +1,558 @@
+use std::{env, rc::Rc};
+
+use mpsgraph::CommandBuffer as MPSCommandBuffer;
+
+use super::{
+ Conv1dPackArguments, Conv1dScanArguments, Conv1dScanKernel,
+ SSDPrefillArguments, SSDPrefillKernel,
+ SSDPrefillMode, SSDUpdateArguments, SSDUpdateKernel, SplitInProjArguments,
+ SplitInProjKernel, conv1d_scan::Conv1dDecodeArguments,
+};
+use crate::{
+ DataType,
+ backends::metal::{
+ KernelDataType, MTLContext, MetalArray,
+ compilation_parameters::CompilationConfig,
+ forward_pass::{
+ ArrayId, ForwardPassState,
+ encodable_with_state::{EncodableWithState, EncodingParameters},
+ transformer_layer,
+ },
+ },
+ config::{DecoderLayerType, mamba::Mamba2Config},
+ parameters::ParameterTree,
+};
+
+pub(crate) struct MambaMixerEncodable {
+ layer_index: usize,
+ config: Mamba2Config,
+ in_projection: Box<dyn EncodableWithState>,
+ out_projection: Box<dyn EncodableWithState>,
+ split_inproj: SplitInProjKernel,
+ conv_scan: Conv1dScanKernel,
+ ssm_prefill: SSDPrefillKernel,
+ ssd_update: SSDUpdateKernel,
+ conv_weight: MetalArray,
+ conv_bias: Option<MetalArray>,
+ gate_bias: MetalArray,
+ skip_connection_weight: MetalArray,
+ prefill_mode: SSDPrefillMode,
+}
+
+impl MambaMixerEncodable {
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn new(
+ mtl_context: &MTLContext,
+ layer_type: DecoderLayerType,
+ mamba_config: Mamba2Config,
+ compilation_config: Rc<CompilationConfig>,
+ layer_index: usize,
+ model_dim: usize,
+ num_heads: usize,
+ head_dim: usize,
+ num_groups: usize,
+ decoder_layer_loader: &ParameterTree<Rc<MTLContext>>,
+ ) -> Self {
+ let _ = (num_heads, head_dim, num_groups);
+ if !matches!(layer_type, DecoderLayerType::StateSpace { .. }) {
+ panic!(
+ "Layer {} marked as transformer but Mamba mixer config provided",
+ layer_index
+ );
+ }
+ let split_tree = resolve_subtree(decoder_layer_loader, &["mixer"]);
+ let conv_tree = resolve_subtree(&split_tree, &["conv", "conv1d"]);
+
+ let data_type: DataType =
+ mamba_config.in_projection_config.activation_precision().into();
+ let kernel_data_type: KernelDataType = data_type.into();
+
+ let in_projection = transformer_layer::linear_block(
+ &mamba_config.in_projection_config,
+ mamba_config.has_in_biases,
+ model_dim,
+ [
+ mamba_config.conv_dim(),
+ mamba_config.inner_dim(),
+ mamba_config.num_heads,
+ ],
+ mtl_context,
+ &resolve_subtree(
+ decoder_layer_loader,
+ &["mixer.in_projection", "mixer.in_proj"],
+ ),
+ ArrayId::Main,
+ ArrayId::SsmInProj,
+ &compilation_config.descriptor_mlp,
+ );
+
+ let out_projection = transformer_layer::linear_block(
+ &mamba_config.out_projection_config,
+ mamba_config.has_out_biases,
+ mamba_config.inner_dim(),
+ [model_dim],
+ mtl_context,
+ &resolve_subtree(
+ decoder_layer_loader,
+ &["mixer.out_projection", "mixer.out_proj"],
+ ),
+ ArrayId::AttentionOutput,
+ ArrayId::Main,
+ &compilation_config.descriptor_mlp,
+ );
+
+ let conv_weight = conv_tree.leaf("weights").unwrap().clone();
+ let conv_bias = if mamba_config.conv_config.has_biases {
+ Some(conv_tree.leaf("biases").unwrap().clone())
+ } else {
+ None
+ };
+ let gate_bias = split_tree.leaf("gate_bias").unwrap().clone();
+ let skip_connection_weight =
+ split_tree.leaf("skip_connection_weight").unwrap().clone();
+
+ let split_inproj =
+ SplitInProjKernel::new(mtl_context, kernel_data_type)
+ .expect("Failed to create split in-projection kernel");
+ let conv_scan = Conv1dScanKernel::new(
+ mtl_context,
+ kernel_data_type,
+ &mamba_config.activation,
+ )
+ .expect("Failed to create conv scan kernel");
+ let ssm_prefill = SSDPrefillKernel::new(mtl_context, kernel_data_type)
+ .expect("Failed to create SSD prefill kernel");
+ let ssd_update = SSDUpdateKernel::new(mtl_context, kernel_data_type)
+ .expect("Failed to create SSD decode kernel");
+ let prefill_mode = resolve_prefill_mode_from_env();
+
+ Self {
+ layer_index,
+ config: mamba_config,
+ in_projection,
+ out_projection,
+ split_inproj,
+ conv_scan,
+ ssm_prefill,
+ ssd_update,
+ conv_weight,
+ conv_bias,
+ gate_bias,
+ skip_connection_weight,
+ prefill_mode,
+ }
+ }
+
+ fn encode_pipeline(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ parameters: &EncodingParameters,
+ ) {
+ let suffix_length = state.aux_buffers_suffix_length();
+ let active_suffix_length = state.active_suffix_length();
+ if suffix_length == 0 || active_suffix_length == 0 {
+ return;
+ }
+
+ self.in_projection.encode(state, command_buffer, parameters);
+ self.split_inproj(state, command_buffer, active_suffix_length);
+ self.run_conv_scan(state, command_buffer, active_suffix_length);
+
+ if suffix_length == 1 {
+ self.run_decode_ssm(state, command_buffer, active_suffix_length);
+ } else {
+ self.run_prefill_ssm(state, command_buffer, active_suffix_length);
+ }
+
+ self.out_projection.encode(state, command_buffer, parameters);
+
+ if parameters.wait_until_completed {
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
+ }
+
+ fn split_inproj(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ suffix_length: usize,
+ ) {
+ let arrays = state.arrays(&[
+ ArrayId::SsmInProj,
+ ArrayId::SsmPacked(self.layer_index),
+ ArrayId::SsmZ(self.layer_index),
+ ArrayId::SsmDt(self.layer_index),
+ ]);
+ let mut in_proj = arrays[0].borrow_mut();
+ let mut conv_inputs = arrays[1].borrow_mut();
+ let mut gate = arrays[2].borrow_mut();
+ let mut dt = arrays[3].borrow_mut();
+
+ let input_buf = unsafe { in_proj.mtl_buffer().to_owned() };
+ let conv_buf = unsafe { conv_inputs.mtl_buffer().to_owned() };
+ let gate_buf = unsafe { gate.mtl_buffer().to_owned() };
+ let dt_buf = unsafe { dt.mtl_buffer().to_owned() };
+ let mut gate_bias = self.gate_bias.clone();
+ let bias_buf = unsafe { gate_bias.mtl_buffer().to_owned() };
+
+ let conv_dim = self.config.conv_dim();
+ let inner_dim = self.config.inner_dim();
+ let num_heads = self.config.num_heads;
+ let total_dim = conv_dim + inner_dim + num_heads;
+
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ let compute = mtl_command_buffer.new_compute_command_encoder();
+ self.split_inproj
+ .encode(
+ &compute,
+ SplitInProjArguments {
+ input: &input_buf,
+ conv_out: &conv_buf,
+ z_out: &gate_buf,
+ dt_out: &dt_buf,
+ z_bias: &bias_buf,
+ total_dim,
+ conv_dim,
+ inner_dim,
+ num_heads,
+ suffix_length,
+ },
+ )
+ .expect("Failed to encode split in-projection kernel");
+ compute.end_encoding();
+ }
+
+ fn run_conv_scan(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ suffix_length: usize,
+ ) {
+ let arrays = state.arrays(&[
+ ArrayId::SsmPacked(self.layer_index),
+ ArrayId::SsmConvState(self.layer_index),
+ ArrayId::SsmX(self.layer_index),
+ ArrayId::SsmB(self.layer_index),
+ ArrayId::SsmC(self.layer_index),
+ ]);
+ let mut conv_inputs = arrays[0].borrow_mut();
+ let mut conv_state = arrays[1].borrow_mut();
+ let mut x_arr = arrays[2].borrow_mut();
+ let mut b_arr = arrays[3].borrow_mut();
+ let mut c_arr = arrays[4].borrow_mut();
+
+ let input_buf = unsafe { conv_inputs.mtl_buffer().to_owned() };
+ let state_buf = unsafe { conv_state.mtl_buffer().to_owned() };
+ let x_buf = unsafe { x_arr.mtl_buffer().to_owned() };
+ let b_buf = unsafe { b_arr.mtl_buffer().to_owned() };
+ let c_buf = unsafe { c_arr.mtl_buffer().to_owned() };
+
+ let mut weight_storage = self.conv_weight.clone();
+ let weight_buf = unsafe { weight_storage.mtl_buffer().to_owned() };
+ let bias_buf = self.conv_bias.as_ref().map(|arr| {
+ let mut storage = arr.clone();
+ unsafe { storage.mtl_buffer().to_owned() }
+ });
+
+ let conv_dim = self.config.conv_dim();
+ let inner_dim = self.config.inner_dim();
+ let proj_dim = self.config.num_groups * self.config.state_dim;
+ let cmd = command_buffer.root_command_buffer().to_owned();
+ let state_stride = self.config.kernel_size.saturating_sub(1);
+ drop(conv_state);
+
+ if suffix_length == 1 {
+ let compute = cmd.new_compute_command_encoder();
+ self.conv_scan
+ .encode_decode(
+ &compute,
+ Conv1dDecodeArguments {
+ x: &input_buf,
+ w: &weight_buf,
+ b: bias_buf.as_ref(),
+ state: &state_buf,
+ x_out: &x_buf,
+ b_out: &b_buf,
+ c_out: &c_buf,
+ next_state: &state_buf,
+ suffix_len: suffix_length,
+ kernel_size: self.config.kernel_size as i32,
+ row_stride: conv_dim,
+ state_stride,
+ channels: conv_dim,
+ inner_dim,
+ proj_dim,
+ },
+ )
+ .expect("Failed to encode conv decode kernel");
+ compute.end_encoding();
+ } else {
+ let padded_buf = if state_stride > 0 {
+ let array = state
+ .conv_padded_buffer()
+ .expect("Missing conv padded buffer");
+ let mut borrow = array.borrow_mut();
+ let buf = unsafe { borrow.mtl_buffer().to_owned() };
+ drop(borrow);
+
+ {
+ let pack_encoder = cmd.new_compute_command_encoder();
+ self.conv_scan
+ .encode_pack(
+ &pack_encoder,
+ Conv1dPackArguments {
+ state_in: &state_buf,
+ x: &input_buf,
+ padded: &buf,
+ state_stride,
+ row_stride: conv_dim,
+ suffix_len: suffix_length,
+ channels: conv_dim,
+ },
+ )
+ .expect("Failed to encode conv pack kernel");
+ pack_encoder.end_encoding();
+ }
+
+ Some(buf)
+ } else {
+ None
+ };
+
+ let conv_source = padded_buf.as_ref().unwrap_or(&input_buf);
+
+ let compute = cmd.new_compute_command_encoder();
+ self.conv_scan
+ .encode(
+ &compute,
+ Conv1dScanArguments {
+ padded: conv_source,
+ w: &weight_buf,
+ b: bias_buf.as_ref(),
+ x_out: &x_buf,
+ b_out: &b_buf,
+ c_out: &c_buf,
+ state_out: &state_buf,
+ suffix_len: suffix_length,
+ kernel_size: self.config.kernel_size as i32,
+ row_stride: conv_dim,
+ state_stride,
+ channels: conv_dim,
+ inner_dim,
+ proj_dim,
+ },
+ )
+ .expect("Failed to encode conv scan kernel");
+ compute.end_encoding();
+ }
+ }
+
+ fn run_prefill_ssm(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ suffix_length: usize,
+ ) {
+ let base_arrays = state.arrays(&[
+ ArrayId::SsmX(self.layer_index),
+ ArrayId::SsmB(self.layer_index),
+ ArrayId::SsmC(self.layer_index),
+ ArrayId::SsmDt(self.layer_index),
+ ArrayId::SsmZ(self.layer_index),
+ ArrayId::SsmState(self.layer_index),
+ ArrayId::AttentionOutput,
+ ]);
+ let mut x = base_arrays[0].borrow_mut();
+ let x_buf = unsafe { x.mtl_buffer().to_owned() };
+ drop(x);
+ let mut b = base_arrays[1].borrow_mut();
+ let b_buf = unsafe { b.mtl_buffer().to_owned() };
+ drop(b);
+ let mut c = base_arrays[2].borrow_mut();
+ let c_buf = unsafe { c.mtl_buffer().to_owned() };
+ drop(c);
+ let mut dt = base_arrays[3].borrow_mut();
+ let dt_buf = unsafe { dt.mtl_buffer().to_owned() };
+ drop(dt);
+ let mut z = base_arrays[4].borrow_mut();
+ let z_buf = unsafe { z.mtl_buffer().to_owned() };
+ drop(z);
+ let mut state_buf = base_arrays[5].borrow_mut();
+ let state_raw = unsafe { state_buf.mtl_buffer().to_owned() };
+ drop(state_buf);
+ let mut out = base_arrays[6].borrow_mut();
+ let out_buf = unsafe { out.mtl_buffer().to_owned() };
+ drop(out);
+
+ let mut skip_weights = self.skip_connection_weight.clone();
+ let skip = unsafe { skip_weights.mtl_buffer().to_owned() };
+
+ let cmd = command_buffer.root_command_buffer().to_owned();
+ let compute = cmd.new_compute_command_encoder();
+ self.ssm_prefill
+ .encode(
+ &compute,
+ SSDPrefillArguments {
+ x: &x_buf,
+ dt: &dt_buf,
+ b: &b_buf,
+ c: &c_buf,
+ d: &skip,
+ z: &z_buf,
+ state: &state_raw,
+ y: &out_buf,
+ suffix_len: suffix_length,
+ group_size: (self.config.num_heads / self.config.num_groups)
+ as i32,
+ state_size: self.config.state_dim as i32,
+ x_strides: [
+ self.config.num_heads * self.config.head_dim,
+ self.config.head_dim,
+ 1,
+ ],
+ dt_strides: [self.config.num_heads, 1],
+ cb_strides: [
+ self.config.num_groups * self.config.state_dim,
+ self.config.state_dim,
+ 1,
+ ],
+ state_strides: [
+ self.config.head_dim * self.config.state_dim,
+ self.config.state_dim,
+ 1,
+ ],
+ channels: self.config.num_heads,
+ head_dim: self.config.head_dim,
+ },
+ self.prefill_mode,
+ )
+ .expect("Failed to encode SSD prefill kernel");
+ compute.end_encoding();
+ }
+
+ fn run_decode_ssm(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ suffix_length: usize,
+ ) {
+ let arrays = state.arrays(&[
+ ArrayId::SsmX(self.layer_index),
+ ArrayId::SsmB(self.layer_index),
+ ArrayId::SsmC(self.layer_index),
+ ArrayId::SsmDt(self.layer_index),
+ ArrayId::SsmZ(self.layer_index),
+ ArrayId::SsmState(self.layer_index),
+ ArrayId::AttentionOutput,
+ ]);
+ let mut x = arrays[0].borrow_mut();
+ let x_buf = unsafe { x.mtl_buffer().to_owned() };
+ drop(x);
+ let mut b = arrays[1].borrow_mut();
+ let b_buf = unsafe { b.mtl_buffer().to_owned() };
+ drop(b);
+ let mut c = arrays[2].borrow_mut();
+ let c_buf = unsafe { c.mtl_buffer().to_owned() };
+ drop(c);
+ let mut dt = arrays[3].borrow_mut();
+ let dt_buf = unsafe { dt.mtl_buffer().to_owned() };
+ drop(dt);
+ let mut z = arrays[4].borrow_mut();
+ let z_buf = unsafe { z.mtl_buffer().to_owned() };
+ drop(z);
+ let mut state_arr = arrays[5].borrow_mut();
+ let state_buf = unsafe { state_arr.mtl_buffer().to_owned() };
+ drop(state_arr);
+ let mut y = arrays[6].borrow_mut();
+ let y_buf = unsafe { y.mtl_buffer().to_owned() };
+ let mut skip_weights = self.skip_connection_weight.clone();
+ let skip_buf = unsafe { skip_weights.mtl_buffer().to_owned() };
+
+ let h = self.config.num_heads;
+ let g = self.config.num_groups;
+ let dh = self.config.head_dim;
+ let n = self.config.state_dim;
+
+ let x_strides = [h * dh, dh, 1usize];
+ let dt_strides = [h, 1usize];
+ let cb_strides = [g * n, n, 1usize];
+ let state_strides = [h * dh * n, dh * n, n, 1usize];
+ let group_size = (h / g) as i32;
+ let state_size = n as i32;
+
+ let cmd = command_buffer.root_command_buffer().to_owned();
+ let compute = cmd.new_compute_command_encoder();
+ self.ssd_update
+ .encode(
+ &compute,
+ SSDUpdateArguments {
+ x: &x_buf,
+ dt: &dt_buf,
+ b: &b_buf,
+ c: &c_buf,
+ d: &skip_buf,
+ z: &z_buf,
+ state: &state_buf,
+ y: &y_buf,
+ next_state: &state_buf,
+ group_size,
+ state_size,
+ x_strides,
+ dt_strides,
+ cb_strides,
+ state_strides,
+ b_size: suffix_length,
+ h_size: h,
+ dh_size: dh,
+ },
+ )
+ .expect("Failed to encode SSD decode kernel");
+ compute.end_encoding();
+ }
+}
+
+fn resolve_prefill_mode_from_env() -> SSDPrefillMode {
+ match env::var("UZU_SSM_PREFILL_MODE") {
+ Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
+ "seq" | "sequential" | "baseline" => SSDPrefillMode::Sequential,
+ "single" | "singlepass" | "single_pass" => {
+ SSDPrefillMode::SinglePass
+ },
+ _ => SSDPrefillMode::SinglePass,
+ },
+ Err(_) => SSDPrefillMode::SinglePass,
+ }
+}
+
+impl EncodableWithState for MambaMixerEncodable {
+ fn encode(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ parameters: &EncodingParameters,
+ ) {
+ self.encode_pipeline(state, command_buffer, parameters);
+ }
+}
+
+fn resolve_subtree<'tree>(
+ loader: &'tree ParameterTree<Rc<MTLContext>>,
+ candidates: &[&str],
+) -> ParameterTree<'tree, Rc<MTLContext>> {
+ for candidate in candidates {
+ if let Ok(tree) = loader.subtree(candidate) {
+ return tree;
+ }
+ }
+
+ let missing =
+ candidates.first().copied().unwrap_or("<missing subtree name>");
+ loader.subtree(missing).unwrap_or_else(|_| {
+ panic!("Unable to resolve parameter subtree '{missing}'")
+ })
+}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/mod.rs b/crates/uzu/src/backends/metal/kernel/ssm/mod.rs
new file mode 100644
index 000000000..8fd1ce3e3
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/mod.rs
@@ -0,0 +1,29 @@
+use crate::backends::metal::{KernelDataType, MTLError};
+
+#[derive(Debug, thiserror::Error)]
+pub enum SSMKernelError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+ #[error("Function not found: {0}")]
+ FunctionNotFound(String),
+}
+
+fn fn_suffix(dt: KernelDataType) -> &'static str {
+ dt.function_name_suffix()
+}
+
+pub mod conv1d_scan;
+pub mod mamba;
+pub mod split_inproj;
+pub mod ssd_prefill;
+pub mod ssd_update;
+pub mod ssm_update;
+
+pub use conv1d_scan::{
+ Conv1dPackArguments, Conv1dScanArguments, Conv1dScanKernel,
+};
+pub(crate) use mamba::MambaMixerEncodable;
+pub use split_inproj::{SplitInProjArguments, SplitInProjKernel};
+pub use ssd_prefill::{SSDPrefillArguments, SSDPrefillKernel, SSDPrefillMode};
+pub use ssd_update::{SSDUpdateArguments, SSDUpdateKernel};
+pub use ssm_update::{SSMUpdateArguments, SSMUpdateKernel};
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.metal b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.metal
new file mode 100644
index 000000000..9f6565fd2
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.metal
@@ -0,0 +1,61 @@
+#include <metal_stdlib>
+#include "../definitions.metal"
+
+using namespace metal;
+
+template <typename T>
+kernel void ssm_split_inproj_kernel(
+ device const T* input [[ buffer(0) ]],
+ device T* conv_out [[ buffer(1) ]],
+ device T* z_out [[ buffer(2) ]],
+ device T* dt_out [[ buffer(3) ]],
+ device const T* z_bias [[ buffer(4) ]],
+ constant const int& total_dim [[ buffer(5) ]],
+ constant const int& conv_dim [[ buffer(6) ]],
+ constant const int& inner_dim [[ buffer(7) ]],
+ constant const int& num_heads [[ buffer(8) ]],
+ uint2 grid_idx [[ thread_position_in_grid ]],
+ uint2 grid_size [[ threads_per_grid ]]
+) {
+ const int row = static_cast<int>(grid_idx.x);
+ const int col = static_cast<int>(grid_idx.y);
+
+ if (row >= grid_size.x || col >= grid_size.y || col >= total_dim) {
+ return;
+ }
+
+ const int input_idx = row * total_dim + col;
+ if (col < conv_dim) {
+ const int dst = row * conv_dim + col;
+ conv_out[dst] = input[input_idx];
+ } else if (col < conv_dim + inner_dim) {
+ const int dst = row * inner_dim + (col - conv_dim);
+ const int bias_idx = col - conv_dim;
+ z_out[dst] = input[input_idx] + z_bias[bias_idx];
+ } else if (col < conv_dim + inner_dim + num_heads) {
+ const int dst = row * num_heads + (col - conv_dim - inner_dim);
+ dt_out[dst] = input[input_idx];
+ }
+}
+
+#define instantiate_ssm_split_inproj_kernel(type_name, type) \
+ template [[host_name("ssm_split_inproj_kernel_" #type_name)]] \
+ kernel void ssm_split_inproj_kernel<type>( \
+ device const type* input [[ buffer(0) ]], \
+ device type* conv_out [[ buffer(1) ]], \
+ device type* z_out [[ buffer(2) ]], \
+ device type* dt_out [[ buffer(3) ]], \
+ device const type* z_bias [[ buffer(4) ]], \
+ constant const int& total_dim [[ buffer(5) ]], \
+ constant const int& conv_dim [[ buffer(6) ]], \
+ constant const int& inner_dim [[ buffer(7) ]], \
+ constant const int& num_heads [[ buffer(8) ]], \
+ uint2 grid_idx [[ thread_position_in_grid ]], \
+ uint2 grid_size [[ threads_per_grid ]] \
+ );
+
+instantiate_ssm_split_inproj_kernel(float, float);
+instantiate_ssm_split_inproj_kernel(bfloat, bfloat);
+instantiate_ssm_split_inproj_kernel(half, half);
+
+#undef instantiate_ssm_split_inproj_kernel
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs
new file mode 100644
index 000000000..37ad2baf3
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs
@@ -0,0 +1,94 @@
+use metal::{Buffer as MTLBuffer, ComputeCommandEncoderRef, MTLSize};
+
+use crate::backends::metal::{KernelDataType, MTLContext};
+
+use super::{SSMKernelError, fn_suffix};
+
+pub struct SplitInProjKernel {
+ pipeline: metal::ComputePipelineState,
+}
+
+pub struct SplitInProjArguments<'a> {
+ pub input: &'a MTLBuffer, // buffer(0) [suffix, total_dim]
+ pub conv_out: &'a MTLBuffer, // buffer(1) [suffix, conv_dim]
+ pub z_out: &'a MTLBuffer, // buffer(2) [suffix, inner_dim]
+ pub dt_out: &'a MTLBuffer, // buffer(3) [suffix, num_heads]
+ pub z_bias: &'a MTLBuffer, // buffer(4) [inner_dim]
+ pub total_dim: usize,
+ pub conv_dim: usize,
+ pub inner_dim: usize,
+ pub num_heads: usize,
+ pub suffix_length: usize,
+}
+
+impl SplitInProjKernel {
+ pub fn new(
+ context: &MTLContext,
+ data_type: KernelDataType,
+ ) -> Result<Self, SSMKernelError> {
+ let fn_name =
+ format!("ssm_split_inproj_kernel_{}", fn_suffix(data_type));
+ let pipeline = context
+ .compute_pipeline_state(&fn_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ Ok(Self {
+ pipeline,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: SplitInProjArguments,
+ ) -> Result<(), SSMKernelError> {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline);
+ compute_encoder.set_buffer(0, Some(args.input), 0);
+ compute_encoder.set_buffer(1, Some(args.conv_out), 0);
+ compute_encoder.set_buffer(2, Some(args.z_out), 0);
+ compute_encoder.set_buffer(3, Some(args.dt_out), 0);
+ compute_encoder.set_buffer(4, Some(args.z_bias), 0);
+
+ let total_dim = args.total_dim as i32;
+ let conv_dim = args.conv_dim as i32;
+ let inner_dim = args.inner_dim as i32;
+ let num_heads = args.num_heads as i32;
+ let suffix = args.suffix_length as u64;
+ let cols = args.total_dim as u64;
+
+ compute_encoder.set_bytes(
+ 5,
+ std::mem::size_of::<i32>() as u64,
+ &total_dim as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 6,
+ std::mem::size_of::<i32>() as u64,
+ &conv_dim as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 7,
+ std::mem::size_of::<i32>() as u64,
+ &inner_dim as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 8,
+ std::mem::size_of::<i32>() as u64,
+ &num_heads as *const i32 as *const _,
+ );
+
+ let threads_per_threadgroup = MTLSize {
+ width: 16,
+ height: 16,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: suffix,
+ height: cols,
+ depth: 1,
+ };
+
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal
new file mode 100644
index 000000000..c39c50ec8
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal
@@ -0,0 +1,404 @@
+#include <metal_stdlib>
+#include <metal_simdgroup>
+#include "../definitions.metal"
+
+using namespace metal;
+
+constant ushort SSM_PREFILL_MAX_STATE = 256;
+
+struct SILU {
+ template <typename T>
+ T operator()(T x) const {
+ float xf = float(x);
+ float y = 1.0f / (1.0f + fast::exp(-fabs(xf)));
+ float out = (xf < 0.0f) ? (1.0f - y) * xf : y * xf;
+ return static_cast<T>(out);
+ }
+};
+
+template <typename T>
+inline T softplus(T x) {
+ float xf = float(x);
+ if (xf > 20.0f) {
+ return x;
+ }
+ return static_cast<T>(log(1.0f + fast::exp(xf)));
+}
+
+template <typename T>
+kernel void ssd_prefill_kernel_64(
+ device const T* x [[ buffer(0) ]], // (suffix, h, dh)
+ device const T* dt_raw [[ buffer(1) ]], // (suffix, h) - raw dt values
+ device const T* B [[ buffer(2) ]], // (suffix, g, n)
+ device const T* C [[ buffer(3) ]], // (suffix, g, n)
+ device const T* D [[ buffer(4) ]], // (h)
+ device const T* z [[ buffer(5) ]], // (suffix, h, dh)
+ device T* state [[ buffer(6) ]], // (h, dh, n)
+ device T* y [[ buffer(7) ]], // (suffix, h, dh)
+ constant const size_t& suffix_len [[ buffer(8) ]],
+ constant const int& group_size [[ buffer(9) ]],
+ constant const int& state_size [[ buffer(10) ]],
+ constant const size_t* x_strides [[ buffer(11) ]],
+ constant const size_t* dt_strides [[ buffer(12) ]],
+ constant const size_t* cb_strides [[ buffer(13) ]],
+ constant const size_t* state_strides [[ buffer(14) ]],
+ constant const uint& num_heads [[ buffer(15) ]],
+ constant const uint& head_dim [[ buffer(16) ]],
+ uint3 tg_pos [[ threadgroup_position_in_grid ]],
+ ushort lane [[ thread_index_in_threadgroup ]]
+) {
+ const uint simd_width = 32;
+ const int state_dim = state_size;
+
+ const uint total_pairs = num_heads * head_dim;
+ const uint pair_idx = tg_pos.x;
+ if (pair_idx >= total_pairs) {
+ return;
+ }
+
+ const uint lane_idx = uint(lane);
+ const uint h_idx = pair_idx / head_dim;
+ const uint dh_idx = pair_idx % head_dim;
+ const uint safe_group = uint(max(group_size, 1));
+ const uint group_idx = h_idx / safe_group;
+
+ const size_t x_token_stride = x_strides[0];
+ const size_t x_head_stride = x_strides[1];
+ const size_t x_dim_stride = x_strides[2];
+ const size_t dt_token_stride = dt_strides[0];
+ const size_t dt_head_stride = dt_strides[1];
+ const size_t cb_token_stride = cb_strides[0];
+ const size_t cb_group_stride = cb_strides[1];
+ const size_t cb_state_stride = cb_strides[2];
+ const size_t state_head_stride = state_strides[0];
+ const size_t state_dim_stride = state_strides[1];
+ const size_t state_inner_stride = state_strides[2];
+
+ const size_t x_base = size_t(h_idx) * x_head_stride
+ + size_t(dh_idx) * x_dim_stride;
+ const size_t dt_base = size_t(h_idx) * dt_head_stride;
+ const size_t state_base =
+ size_t(h_idx) * state_head_stride + size_t(dh_idx) * state_dim_stride;
+ const size_t cb_group_base = size_t(group_idx) * cb_group_stride;
+ const float d_scalar = float(D[h_idx]);
+
+ const uint idx0 = lane_idx;
+ const uint idx1 = lane_idx + simd_width;
+
+ float state0 = 0.0f;
+ float state1 = 0.0f;
+ size_t state_idx0 = 0;
+ size_t state_idx1 = 0;
+ state_idx0 = state_base + size_t(idx0) * state_inner_stride;
+ state0 = float(state[state_idx0]);
+
+ state_idx1 = state_base + size_t(idx1) * state_inner_stride;
+ state1 = float(state[state_idx1]);
+
+ size_t cb_idx0 = 0;
+ size_t cb_idx1 = 0;
+ cb_idx0 = cb_group_base + size_t(idx0) * cb_state_stride;
+ cb_idx1 = cb_group_base + size_t(idx1) * cb_state_stride;
+
+ for (size_t token = 0; token < suffix_len; ++token) {
+ const size_t x_idx = token * x_token_stride + x_base;
+ const size_t dt_idx = token * dt_token_stride + dt_base;
+
+ const float x_val = float(x[x_idx]);
+ const float decay_val = fast::exp(-float(softplus(float(dt_raw[dt_idx]))));
+ const float gate = float(SILU{}(z[x_idx]));
+ const float skip = d_scalar * x_val;
+ const float dt_scaled_input = x_val;
+
+ float contrib = 0.0f;
+ const float new_state0 = decay_val * state0 + dt_scaled_input * float(B[cb_idx0]);
+ state0 = new_state0;
+ contrib += new_state0 * float(C[cb_idx0]);
+ cb_idx0 += cb_token_stride;
+
+ const float new_state1 = decay_val * state1 + dt_scaled_input * float(B[cb_idx1]);
+ state1 = new_state1;
+ contrib += new_state1 * float(C[cb_idx1]);
+ cb_idx1 += cb_token_stride;
+
+ float dot = simd_sum(contrib);
+ if (lane_idx == 0) {
+ y[x_idx] = static_cast<T>((skip + dot) * gate);
+ }
+ }
+
+ state[state_idx0] = static_cast<T>(state0);
+ state[state_idx1] = static_cast<T>(state1);
+}
+
+#define instantiate_ssd_prefill_kernel_64(type_name, type) \
+ template [[host_name("ssd_prefill_kernel_64_" #type_name)]] \
+ kernel void ssd_prefill_kernel_64<type>( \
+ device const type* x [[ buffer(0) ]], \
+ device const type* dt_raw [[ buffer(1) ]], \
+ device const type* B [[ buffer(2) ]], \
+ device const type* C [[ buffer(3) ]], \
+ device const type* D [[ buffer(4) ]], \
+ device const type* z [[ buffer(5) ]], \
+ device type* state [[ buffer(6) ]], \
+ device type* y [[ buffer(7) ]], \
+ constant const size_t& suffix_len [[ buffer(8) ]], \
+ constant const int& group_size [[ buffer(9) ]], \
+ constant const int& state_size [[ buffer(10) ]], \
+ constant const size_t* x_strides [[ buffer(11) ]], \
+ constant const size_t* dt_strides [[ buffer(12) ]], \
+ constant const size_t* cb_strides [[ buffer(13) ]], \
+ constant const size_t* state_strides [[ buffer(14) ]], \
+ constant const uint& num_heads [[ buffer(15) ]], \
+ constant const uint& head_dim [[ buffer(16) ]], \
+ uint3 tg_pos [[ threadgroup_position_in_grid ]], \
+ ushort lane [[ thread_index_in_threadgroup ]] \
+ );
+
+instantiate_ssd_prefill_kernel_64(float, float);
+instantiate_ssd_prefill_kernel_64(bfloat, bfloat);
+instantiate_ssd_prefill_kernel_64(half, half);
+
+#undef instantiate_ssd_prefill_kernel_64
+
+template <typename T>
+kernel void ssd_prefill_kernel(
+ device const T* x [[ buffer(0) ]], // (suffix, h, dh)
+ device const T* dt_raw [[ buffer(1) ]], // (suffix, h) - raw dt values
+ device const T* B [[ buffer(2) ]], // (suffix, g, n)
+ device const T* C [[ buffer(3) ]], // (suffix, g, n)
+ device const T* D [[ buffer(4) ]], // (h)
+ device const T* z [[ buffer(5) ]], // (suffix, h, dh)
+ device T* state [[ buffer(6) ]], // (h, dh, n)
+ device T* y [[ buffer(7) ]], // (suffix, h, dh)
+ constant const size_t& suffix_len [[ buffer(8) ]],
+ constant const int& group_size [[ buffer(9) ]],
+ constant const int& state_size [[ buffer(10) ]],
+ constant const size_t* x_strides [[ buffer(11) ]],
+ constant const size_t* dt_strides [[ buffer(12) ]],
+ constant const size_t* cb_strides [[ buffer(13) ]],
+ constant const size_t* state_strides [[ buffer(14) ]],
+ constant const uint& num_heads [[ buffer(15) ]],
+ constant const uint& head_dim [[ buffer(16) ]],
+ uint3 tg_pos [[ threadgroup_position_in_grid ]],
+ ushort lane [[ thread_index_in_threadgroup ]]
+) {
+ const uint simd_width = 32;
+ const int state_dim = state_size;
+
+ const uint total_pairs = num_heads * head_dim;
+ const uint pair_idx = tg_pos.x;
+ if (pair_idx >= total_pairs) {
+ return;
+ }
+
+ const uint lane_idx = uint(lane);
+ const uint h_idx = pair_idx / head_dim;
+ const uint dh_idx = pair_idx % head_dim;
+ const uint safe_group = uint(max(group_size, 1));
+ const uint group_idx = h_idx / safe_group;
+
+ const size_t x_token_stride = x_strides[0];
+ const size_t x_head_stride = x_strides[1];
+ const size_t x_dim_stride = x_strides[2];
+ const size_t dt_token_stride = dt_strides[0];
+ const size_t dt_head_stride = dt_strides[1];
+ const size_t cb_token_stride = cb_strides[0];
+ const size_t cb_group_stride = cb_strides[1];
+ const size_t cb_state_stride = cb_strides[2];
+ const size_t state_head_stride = state_strides[0];
+ const size_t state_dim_stride = state_strides[1];
+ const size_t state_inner_stride = state_strides[2];
+
+ const size_t x_base = size_t(h_idx) * x_head_stride + size_t(dh_idx) * x_dim_stride;
+ const size_t dt_base = size_t(h_idx) * dt_head_stride;
+ const size_t state_base = size_t(h_idx) * state_head_stride + size_t(dh_idx) * state_dim_stride;
+ const size_t cb_group_base = size_t(group_idx) * cb_group_stride;
+ const float d_scalar = float(D[h_idx]);
+
+ const int max_chunks = SSM_PREFILL_MAX_STATE / simd_width;
+ const int chunk_count =
+ (state_dim + int(simd_width) - 1) / int(simd_width);
+ if (state_dim <= 0 || chunk_count > max_chunks) {
+ return;
+ }
+
+ thread float lane_states[SSM_PREFILL_MAX_STATE / 32];
+
+ #pragma unroll
+ for (int chunk = 0; chunk < chunk_count; ++chunk) {
+ const int idx = chunk * int(simd_width) + int(lane_idx);
+ const size_t state_idx =
+ state_base + size_t(idx) * state_inner_stride;
+ lane_states[chunk] = float(state[state_idx]);
+ }
+
+ for (size_t token = 0; token < suffix_len; ++token) {
+ const size_t x_idx = token * x_token_stride + x_base;
+ const size_t dt_idx = token * dt_token_stride + dt_base;
+
+ const float x_val = float(x[x_idx]);
+ const float decay_val = fast::exp(-float(softplus(float(dt_raw[dt_idx]))));
+ const float gate = float(SILU{}(z[x_idx]));
+ const float skip = d_scalar * x_val;
+ const float dt_scaled_input = x_val;
+
+ float contrib_sum = 0.0f;
+ #pragma unroll
+ for (int chunk = 0; chunk < chunk_count; ++chunk) {
+ const int idx = chunk * int(simd_width) + int(lane_idx);
+ const size_t cb_idx = cb_group_base + size_t(idx) * cb_state_stride + token * cb_token_stride;
+
+ const float new_state = decay_val * lane_states[chunk] + dt_scaled_input * float(B[cb_idx]);
+ lane_states[chunk] = new_state;
+ contrib_sum += new_state * float(C[cb_idx]);
+ }
+
+ float dot = simd_sum(contrib_sum);
+ if (lane_idx == 0) {
+ y[x_idx] = static_cast<T>((skip + dot) * gate);
+ }
+ }
+
+ #pragma unroll
+ for (int chunk = 0; chunk < chunk_count; ++chunk) {
+ const int idx = chunk * int(simd_width) + int(lane_idx);
+ const size_t state_idx = state_base + size_t(idx) * state_inner_stride;
+ state[state_idx] = static_cast<T>(lane_states[chunk]);
+ }
+}
+
+#define instantiate_ssd_prefill_kernel(type_name, type) \
+ template [[host_name("ssd_prefill_kernel_" #type_name)]] \
+ kernel void ssd_prefill_kernel<type>( \
+ device const type* x [[ buffer(0) ]], \
+ device const type* dt_raw [[ buffer(1) ]], \
+ device const type* B [[ buffer(2) ]], \
+ device const type* C [[ buffer(3) ]], \
+ device const type* D [[ buffer(4) ]], \
+ device const type* z [[ buffer(5) ]], \
+ device type* state [[ buffer(6) ]], \
+ device type* y [[ buffer(7) ]], \
+ constant const size_t& suffix_len [[ buffer(8) ]], \
+ constant const int& group_size [[ buffer(9) ]], \
+ constant const int& state_size [[ buffer(10) ]], \
+ constant const size_t* x_strides [[ buffer(11) ]], \
+ constant const size_t* dt_strides [[ buffer(12) ]], \
+ constant const size_t* cb_strides [[ buffer(13) ]], \
+ constant const size_t* state_strides [[ buffer(14) ]], \
+ constant const uint& num_heads [[ buffer(15) ]], \
+ constant const uint& head_dim [[ buffer(16) ]], \
+ uint3 tg_pos [[ threadgroup_position_in_grid ]], \
+ ushort lane [[ thread_index_in_threadgroup ]] \
+ );
+
+instantiate_ssd_prefill_kernel(float, float);
+instantiate_ssd_prefill_kernel(bfloat, bfloat);
+instantiate_ssd_prefill_kernel(half, half);
+
+#undef instantiate_ssd_prefill_kernel
+
+template <typename T>
+kernel void ssd_prefill_kernel_sequential(
+ device const T* x [[ buffer(0) ]], // (suffix, h, dh)
+ device const T* dt_raw [[ buffer(1) ]], // (suffix, h) - raw dt values
+ device const T* B [[ buffer(2) ]], // (suffix, g, n)
+ device const T* C [[ buffer(3) ]], // (suffix, g, n)
+ device const T* D [[ buffer(4) ]], // (h)
+ device const T* z [[ buffer(5) ]], // (suffix, h, dh)
+ device T* state [[ buffer(6) ]], // (h, dh, n)
+ device T* y [[ buffer(7) ]], // (suffix, h, dh)
+ constant const size_t& suffix_len [[ buffer(8) ]],
+ constant const int& group_size [[ buffer(9) ]],
+ constant const int& state_size [[ buffer(10) ]],
+ constant const size_t* x_strides [[ buffer(11) ]],
+ constant const size_t* dt_strides [[ buffer(12) ]],
+ constant const size_t* cb_strides [[ buffer(13) ]],
+ constant const size_t* state_strides [[ buffer(14) ]],
+ uint3 tid [[ thread_position_in_grid ]],
+ uint3 grid_dim [[ threads_per_grid ]]
+) {
+ const uint h_idx = tid.x;
+ const uint dh_idx = tid.y;
+ if (h_idx >= grid_dim.x || dh_idx >= grid_dim.y) {
+ return;
+ }
+
+ const uint safe_group = uint(max(group_size, 1));
+ const uint group_idx = h_idx / safe_group;
+ device T* state_row =
+ state + size_t(h_idx) * state_strides[0] + size_t(dh_idx) * state_strides[1];
+
+ for (size_t token = 0; token < suffix_len; ++token) {
+ const size_t x_idx = token * x_strides[0]
+ + size_t(h_idx) * x_strides[1]
+ + size_t(dh_idx) * x_strides[2];
+ const size_t dt_idx =
+ token * dt_strides[0] + size_t(h_idx) * dt_strides[1];
+ const size_t cb_base =
+ token * cb_strides[0] + group_idx * cb_strides[1];
+
+ const T this_x = x[x_idx];
+ const T dt_raw_val = dt_raw[dt_idx];
+ const T this_dt = softplus(dt_raw_val);
+ const T this_decay = static_cast<T>(fast::exp(-float(this_dt)));
+ const T this_D = D[h_idx];
+ const T this_z = SILU{}(z[x_idx]);
+ const T dt_scaled_input = this_x;
+
+ T acc = T(0);
+ int s = 0;
+ const int vec_bound = (state_size / 4) * 4;
+ for (; s < vec_bound; s += 4) {
+ const size_t state_idx = s * state_strides[2];
+ const size_t cb_idx = cb_base + s * cb_strides[2];
+ auto prev_state = *reinterpret_cast<device vec<T, 4>*>(state_row + state_idx);
+ auto b_vec = *reinterpret_cast<device const vec<T, 4>*>(B + cb_idx);
+ auto c_vec = *reinterpret_cast<device const vec<T, 4>*>(C + cb_idx);
+ vec<T, 4> new_state = prev_state * this_decay + b_vec * dt_scaled_input;
+ *reinterpret_cast<device vec<T, 4>*>(state_row + state_idx) = new_state;
+ vec<T, 4> prod = new_state * c_vec;
+ acc += prod.x + prod.y + prod.z + prod.w;
+ }
+ for (; s < state_size; ++s) {
+ const size_t state_idx = s * state_strides[2];
+ const T prev_state = state_row[state_idx];
+ const size_t cb_idx = cb_base + s * cb_strides[2];
+ const T new_state = prev_state * this_decay + B[cb_idx] * dt_scaled_input;
+ state_row[state_idx] = new_state;
+ acc += new_state * C[cb_idx];
+ }
+
+ acc += this_D * this_x;
+ acc *= this_z;
+ y[x_idx] = acc;
+ }
+}
+
+#define instantiate_ssd_prefill_kernel_sequential(type_name, type) \
+ template [[host_name("ssd_prefill_kernel_sequential_" #type_name)]] \
+ kernel void ssd_prefill_kernel_sequential<type>( \
+ device const type* x [[ buffer(0) ]], \
+ device const type* dt_raw [[ buffer(1) ]], \
+ device const type* B [[ buffer(2) ]], \
+ device const type* C [[ buffer(3) ]], \
+ device const type* D [[ buffer(4) ]], \
+ device const type* z [[ buffer(5) ]], \
+ device type* state [[ buffer(6) ]], \
+ device type* y [[ buffer(7) ]], \
+ constant const size_t& suffix_len [[ buffer(8) ]], \
+ constant const int& group_size [[ buffer(9) ]], \
+ constant const int& state_size [[ buffer(10) ]], \
+ constant const size_t* x_strides [[ buffer(11) ]], \
+ constant const size_t* dt_strides [[ buffer(12) ]], \
+ constant const size_t* cb_strides [[ buffer(13) ]], \
+ constant const size_t* state_strides [[ buffer(14) ]], \
+ uint3 tid [[ thread_position_in_grid ]], \
+ uint3 grid_dim [[ threads_per_grid ]] \
+ );
+
+instantiate_ssd_prefill_kernel_sequential(float, float);
+instantiate_ssd_prefill_kernel_sequential(bfloat, bfloat);
+instantiate_ssd_prefill_kernel_sequential(half, half);
+
+#undef instantiate_ssd_prefill_kernel_sequential
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs
new file mode 100644
index 000000000..6cbc21852
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs
@@ -0,0 +1,204 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use super::{SSMKernelError, fn_suffix};
+use crate::backends::metal::{KernelDataType, MTLContext};
+
+const SSD_PREFILL_SINGLE_THREADS: u64 = 32;
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum SSDPrefillMode {
+ Sequential,
+ SinglePass,
+}
+
+pub struct SSDPrefillKernel {
+ sequential: MTLComputePipelineState,
+ single_pass: MTLComputePipelineState,
+ single_pass_64: MTLComputePipelineState,
+}
+
+pub struct SSDPrefillArguments<'a> {
+ pub x: &'a MTLBuffer,
+ pub dt: &'a MTLBuffer, // raw dt values
+ pub b: &'a MTLBuffer,
+ pub c: &'a MTLBuffer,
+ pub d: &'a MTLBuffer,
+ pub z: &'a MTLBuffer,
+ pub state: &'a MTLBuffer,
+ pub y: &'a MTLBuffer,
+ pub suffix_len: usize,
+ pub group_size: i32,
+ pub state_size: i32,
+ pub x_strides: [usize; 3],
+ pub dt_strides: [usize; 2],
+ pub cb_strides: [usize; 3],
+ pub state_strides: [usize; 3],
+ pub channels: usize,
+ pub head_dim: usize,
+}
+
+impl SSDPrefillKernel {
+ pub fn new(
+ context: &MTLContext,
+ data_type: KernelDataType,
+ ) -> Result<Self, SSMKernelError> {
+ let sequential_name =
+ format!("ssd_prefill_kernel_sequential_{}", fn_suffix(data_type));
+ let single_name =
+ format!("ssd_prefill_kernel_{}", fn_suffix(data_type));
+ let single_64_name =
+ format!("ssd_prefill_kernel_64_{}", fn_suffix(data_type));
+ let sequential = context
+ .compute_pipeline_state(&sequential_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ let single_pass = context
+ .compute_pipeline_state(&single_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ let single_pass_64 = context
+ .compute_pipeline_state(&single_64_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ Ok(Self {
+ sequential,
+ single_pass,
+ single_pass_64,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: SSDPrefillArguments,
+ mode: SSDPrefillMode,
+ ) -> Result<(), SSMKernelError> {
+ match mode {
+ SSDPrefillMode::Sequential => {
+ self.encode_sequential(compute_encoder, &args)
+ },
+ SSDPrefillMode::SinglePass => {
+ self.encode_single(compute_encoder, &args)
+ },
+ }
+ }
+
+ fn encode_sequential(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: &SSDPrefillArguments,
+ ) -> Result<(), SSMKernelError> {
+ if args.channels == 0 || args.head_dim == 0 || args.suffix_len == 0 {
+ return Ok(());
+ }
+ compute_encoder.set_compute_pipeline_state(&self.sequential);
+ self.bind_common_buffers(compute_encoder, args);
+ let threads_per_threadgroup = MTLSize {
+ width: 32,
+ height: 32,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: args.channels as u64,
+ height: args.head_dim as u64,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+
+ fn encode_single(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: &SSDPrefillArguments,
+ ) -> Result<(), SSMKernelError> {
+ if args.channels == 0 || args.head_dim == 0 || args.suffix_len == 0 {
+ return Ok(());
+ }
+ if args.state_size == 64 {
+ compute_encoder.set_compute_pipeline_state(&self.single_pass_64);
+ } else {
+ compute_encoder.set_compute_pipeline_state(&self.single_pass);
+ }
+ self.bind_common_buffers(compute_encoder, args);
+ let channels = args.channels as u32;
+ let head_dim = args.head_dim as u32;
+ compute_encoder.set_bytes(
+ 15,
+ size_of::<u32>() as u64,
+ &channels as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 16,
+ size_of::<u32>() as u64,
+ &head_dim as *const u32 as *const _,
+ );
+ let threads_per_threadgroup = MTLSize {
+ width: SSD_PREFILL_SINGLE_THREADS,
+ height: 1,
+ depth: 1,
+ };
+ let pair_count = args.channels as u64 * args.head_dim as u64;
+ let total_threads = MTLSize {
+ width: pair_count * SSD_PREFILL_SINGLE_THREADS,
+ height: 1,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+
+ fn bind_common_buffers(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: &SSDPrefillArguments,
+ ) {
+ compute_encoder.set_buffer(0, Some(args.x), 0);
+ compute_encoder.set_buffer(1, Some(args.dt), 0);
+ compute_encoder.set_buffer(2, Some(args.b), 0);
+ compute_encoder.set_buffer(3, Some(args.c), 0);
+ compute_encoder.set_buffer(4, Some(args.d), 0);
+ compute_encoder.set_buffer(5, Some(args.z), 0);
+ compute_encoder.set_buffer(6, Some(args.state), 0);
+ compute_encoder.set_buffer(7, Some(args.y), 0);
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<usize>() as u64,
+ &args.suffix_len as *const usize as *const _,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<i32>() as u64,
+ &args.group_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<i32>() as u64,
+ &args.state_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ (3 * size_of::<usize>()) as u64,
+ args.x_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 12,
+ (2 * size_of::<usize>()) as u64,
+ args.dt_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 13,
+ (3 * size_of::<usize>()) as u64,
+ args.cb_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 14,
+ (3 * size_of::<usize>()) as u64,
+ args.state_strides.as_ptr() as *const _,
+ );
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.metal b/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.metal
new file mode 100644
index 000000000..048023aca
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.metal
@@ -0,0 +1,105 @@
+#include <metal_stdlib>
+#include "../definitions.metal"
+
+using namespace metal;
+
+struct SILU {
+ template <typename T>
+ T operator()(T x) {
+ float xf = float(x);
+ float y = 1.0f / (1.0f + fast::exp(-fabs(xf)));
+ float out = (xf < 0.0f) ? (1.0f - y) * xf : y * xf;
+ return static_cast<T>(out);
+ }
+};
+
+template <typename T>
+inline T softplus(T x) {
+ float xf = float(x);
+ if (xf > 20.0f) {
+ return x;
+ }
+ return static_cast<T>(log(1.0f + fast::exp(xf)));
+}
+
+template <typename T>
+kernel void ssd_update_kernel(
+ // Input
+ device const T* x [[ buffer(0) ]], // (b, h, dh)
+ device const T* dt_raw [[ buffer(1) ]], // (b, h)
+ device const T* B [[ buffer(2) ]], // (b, g, n)
+ device const T* C [[ buffer(3) ]], // (b, g, n)
+ device const T* D [[ buffer(4) ]], // (h)
+ device const T* z [[ buffer(5) ]], // (b, d)
+ device const T* state [[ buffer(6) ]], // (b, h, dh, n)
+ device T* y [[ buffer(7) ]],
+ device T* next_state [[ buffer(8) ]],
+ // Parameters
+ constant const int& group_size [[ buffer(9) ]], // h = group_size * g
+ constant const int& state_size [[ buffer(10) ]],
+ // Strides
+ constant const size_t* x_strides [[ buffer(11) ]],
+ constant const size_t* dt_strides [[ buffer(12) ]],
+ constant const size_t* CB_strides [[ buffer(13) ]],
+ constant const size_t* state_strides [[ buffer(14) ]],
+ // Grid
+ uint3 grid_idx [[ thread_position_in_grid ]],
+ uint3 grid_size [[ threads_per_grid ]]
+) {
+ const int b_idx = grid_idx.x;
+ const int h_idx = grid_idx.y;
+ const int dh_idx = grid_idx.z;
+
+ const int CB_start_idx = static_cast<int>(b_idx * CB_strides[0] + (h_idx / group_size) * CB_strides[1]);
+ const int x_idx = static_cast<int>(b_idx * x_strides[0] + h_idx * x_strides[1] + dh_idx * x_strides[2]);
+ const int dt_idx = static_cast<int>(b_idx * dt_strides[0] + h_idx * dt_strides[1]);
+ const int state_start_idx = static_cast<int>(b_idx * state_strides[0] + h_idx * state_strides[1] + dh_idx * state_strides[2]);
+
+ // load data
+ T this_x = x[x_idx];
+ T dt_raw_val = dt_raw[dt_idx];
+ T this_dt = softplus(dt_raw_val);
+ T this_decay = static_cast<T>(fast::exp(-float(this_dt)));
+ T this_D = D[h_idx];
+ T this_z = z[x_idx];
+ this_z = SILU{}(this_z);
+ T dt_scaled_input = this_x;
+
+ T temp = T(0);
+ #pragma unroll
+ for (int i = 0; i < state_size; ++i) {
+ int CB_idx = CB_start_idx + i;
+ int state_idx = state_start_idx + i;
+ T this_new_state = state[state_idx] * this_decay + B[CB_idx] * dt_scaled_input;
+ next_state[state_idx] = this_new_state;
+ temp = temp + this_new_state * C[CB_idx];
+ }
+ temp = temp + this_D * this_x;
+ temp = temp * this_z;
+ y[x_idx] = temp;
+}
+
+#define instantiate_ssd_update_kernel(type_name, type) \
+ template [[host_name("ssd_update_kernel_" #type_name)]] \
+ kernel void ssd_update_kernel<type>( \
+ device const type* x [[buffer(0)]], \
+ device const type* dt_raw [[buffer(1)]], \
+ device const type* B [[buffer(2)]], \
+ device const type* C [[buffer(3)]], \
+ device const type* D [[buffer(4)]], \
+ device const type* z [[buffer(5)]], \
+ device const type* state [[buffer(6)]], \
+ device type* y [[buffer(7)]], \
+ device type* next_state [[buffer(8)]], \
+ constant const int& group_size [[buffer(9)]], \
+ constant const int& state_size [[buffer(10)]], \
+ constant const size_t* x_strides [[buffer(11)]], \
+ constant const size_t* dt_strides [[buffer(12)]], \
+ constant const size_t* CB_strides [[buffer(13)]], \
+ constant const size_t* state_strides [[buffer(14)]], \
+ uint3 grid_idx [[thread_position_in_grid]], \
+ uint3 grid_size [[threads_per_grid]]);
+
+instantiate_ssd_update_kernel(float, float);
+instantiate_ssd_update_kernel(bfloat, bfloat);
+instantiate_ssd_update_kernel(half, half);
\ No newline at end of file
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.rs b/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.rs
new file mode 100644
index 000000000..a9a9da0d4
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssd_update.rs
@@ -0,0 +1,112 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use super::{SSMKernelError, fn_suffix};
+use crate::backends::metal::{KernelDataType, MTLContext};
+
+pub struct SSDUpdateKernel {
+ pipeline: MTLComputePipelineState,
+}
+
+pub struct SSDUpdateArguments<'a> {
+ pub x: &'a MTLBuffer, // buffer(0) (b, h, dh)
+ pub dt: &'a MTLBuffer, // buffer(1) (b, h) - raw dt values
+ pub b: &'a MTLBuffer, // buffer(2) (b, g, n)
+ pub c: &'a MTLBuffer, // buffer(3) (b, g, n)
+ pub d: &'a MTLBuffer, // buffer(4) (h)
+ pub z: &'a MTLBuffer, // buffer(5) (b, d)
+ pub state: &'a MTLBuffer, // buffer(6) (b, h, dh, n)
+ pub y: &'a MTLBuffer, // buffer(7)
+ pub next_state: &'a MTLBuffer, // buffer(8)
+ pub group_size: i32, // buffer(9)
+ pub state_size: i32, // buffer(10)
+ pub x_strides: [usize; 3], // buffer(11)
+ pub dt_strides: [usize; 2], // buffer(12)
+ pub cb_strides: [usize; 3], // buffer(13)
+ pub state_strides: [usize; 4], // buffer(14)
+ pub b_size: usize,
+ pub h_size: usize,
+ pub dh_size: usize,
+}
+
+impl SSDUpdateKernel {
+ pub fn new(
+ context: &MTLContext,
+ data_type: KernelDataType,
+ ) -> Result<Self, SSMKernelError> {
+ let fn_name = format!("ssd_update_kernel_{}", fn_suffix(data_type));
+ let pipeline = context
+ .compute_pipeline_state(&fn_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ Ok(Self {
+ pipeline,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: SSDUpdateArguments,
+ ) -> Result<(), SSMKernelError> {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline);
+
+ compute_encoder.set_buffer(0, Some(args.x), 0);
+ compute_encoder.set_buffer(1, Some(args.dt), 0);
+ compute_encoder.set_buffer(2, Some(args.b), 0);
+ compute_encoder.set_buffer(3, Some(args.c), 0);
+ compute_encoder.set_buffer(4, Some(args.d), 0);
+ compute_encoder.set_buffer(5, Some(args.z), 0);
+ compute_encoder.set_buffer(6, Some(args.state), 0);
+ compute_encoder.set_buffer(7, Some(args.y), 0);
+ compute_encoder.set_buffer(8, Some(args.next_state), 0);
+
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<i32>() as u64,
+ &args.group_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<i32>() as u64,
+ &args.state_size as *const i32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ (3 * size_of::<usize>()) as u64,
+ args.x_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 12,
+ (2 * size_of::<usize>()) as u64,
+ args.dt_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 13,
+ (3 * size_of::<usize>()) as u64,
+ args.cb_strides.as_ptr() as *const _,
+ );
+ compute_encoder.set_bytes(
+ 14,
+ (4 * size_of::<usize>()) as u64,
+ args.state_strides.as_ptr() as *const _,
+ );
+
+ let threads_per_threadgroup = MTLSize {
+ width: 32,
+ height: 32,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: args.b_size as u64,
+ height: args.h_size as u64,
+ depth: args.dh_size as u64,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.metal b/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.metal
new file mode 100644
index 000000000..b88fb4af1
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.metal
@@ -0,0 +1,107 @@
+#include <metal_stdlib>
+#include "../definitions.metal"
+
+using namespace metal;
+
+struct SILU {
+ template <typename T>
+ T operator()(T x) {
+ float xf = float(x);
+ float y = 1.0f / (1.0f + fast::exp(-fabs(xf)));
+ float out = (xf < 0.0f) ? (1.0f - y) * xf : y * xf;
+ return static_cast<T>(out);
+ }
+};
+
+struct Softplus {
+ template <typename T>
+ T operator()(T x) {
+ float xf = float(x);
+ float y = log(1.0f + fast::exp(xf));
+ return static_cast<T>((xf > 20.0f) ? xf : y);
+ }
+};
+
+struct Exp {
+ template <typename T>
+ T operator()(T x) {
+ float xf = float(x);
+ return static_cast<T>(fast::exp(xf));
+ };
+};
+
+// Mamba SSM naming:
+// X – SILU-activated hidden stream after the conv block
+// Z – gate activations that modulate the residual output
+// A – diagonal state transition spectrum (constant per layer)
+// B – input projection that injects X into the state
+// C – output projection from state to residual
+// D – per-head skip/identity weight
+
+template <typename T>
+kernel void ssm_update_kernel(
+ device const T* x [[ buffer(0) ]], // (b, h) hidden stream X
+ device const T* dt [[ buffer(1) ]], // (b, h) delta / step size
+ device const T* A [[ buffer(2) ]], // (n) spectrum A
+ device const T* B [[ buffer(3) ]], // (b, n) input projection B
+ device const T* C [[ buffer(4) ]], // (b, n) output projection C
+ device const T* D [[ buffer(5) ]], // (h) skip weights D
+ device const T* z [[ buffer(6) ]], // (b, h) gate Z
+ device const T* state [[ buffer(7) ]], // (b, h, n)
+ device T* y [[ buffer(8) ]], // (b, h)
+ device T* next_state [[ buffer(9) ]], // (b, h, n)
+ uint3 grid_idx [[ thread_position_in_grid ]],
+ uint3 grid_size [[ threads_per_grid ]]
+) {
+ const int state_size = 16; // matches reference
+ const int channel_size = grid_size.y;
+
+ const int batch_idx = grid_idx.x;
+ const int channel_idx = grid_idx.y;
+
+ const int cb_start_idx = batch_idx * state_size;
+ const int x_idx = batch_idx * channel_size + channel_idx;
+ const int state_start_idx = x_idx * state_size;
+
+ T this_x = x[x_idx];
+ this_x = SILU{}(this_x);
+
+ T this_z = z[x_idx];
+ this_z = SILU{}(this_z);
+
+ T delta = Softplus{}(dt[x_idx]);
+
+ T temp = T(0);
+ #pragma unroll
+ for (int i = 0; i < state_size; ++i) {
+ int cb_idx = cb_start_idx + i;
+ int state_idx = state_start_idx + i;
+ T this_new_state = state[state_idx] * Exp{}(A[i] * delta) + B[cb_idx] * delta * this_x;
+ next_state[state_idx] = this_new_state;
+ temp = temp + this_new_state * C[cb_idx];
+ }
+ temp = temp + D[channel_idx] * this_x;
+ temp = temp * this_z;
+ y[x_idx] = temp;
+}
+
+#define instantiate_ssm_update_kernel(type_name, type) \
+ template [[host_name("ssm_update_kernel_" #type_name)]] \
+ kernel void ssm_update_kernel<type>( \
+ device const type* x [[ buffer(0) ]], \
+ device const type* dt [[ buffer(1) ]], \
+ device const type* A [[ buffer(2) ]], \
+ device const type* B [[ buffer(3) ]], \
+ device const type* C [[ buffer(4) ]], \
+ device const type* D [[ buffer(5) ]], \
+ device const type* z [[ buffer(6) ]], \
+ device const type* state [[ buffer(7) ]], \
+ device type* y [[ buffer(8) ]], \
+ device type* next_state [[ buffer(9) ]], \
+ uint3 grid_idx [[ thread_position_in_grid ]], \
+ uint3 grid_size [[ threads_per_grid ]]);
+
+instantiate_ssm_update_kernel(float, float);
+instantiate_ssm_update_kernel(bfloat, bfloat);
+instantiate_ssm_update_kernel(half, half);
+
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.rs b/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.rs
new file mode 100644
index 000000000..c5bd9a337
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssm_update.rs
@@ -0,0 +1,84 @@
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use super::{SSMKernelError, fn_suffix};
+use crate::backends::metal::{KernelDataType, MTLContext};
+
+pub struct SSMUpdateKernel {
+ pipeline: MTLComputePipelineState,
+}
+
+pub struct SSMUpdateArguments<'a> {
+ /// X – Silu-activated hidden stream (per head/channel) coming from the conv.
+ pub x: &'a MTLBuffer, // buffer(0)
+ /// Δt – learned step sizes per head.
+ pub dt: &'a MTLBuffer, // buffer(1)
+ /// A – diagonal decay coefficients shared across tokens (eigenvalues).
+ pub a: &'a MTLBuffer, // buffer(2)
+ /// B – input projection that injects X into the state space.
+ pub b: &'a MTLBuffer, // buffer(3)
+ /// C – output projection that maps state to residual updates.
+ pub c: &'a MTLBuffer, // buffer(4)
+ /// D – per-head skip/identity weights.
+ pub d: &'a MTLBuffer, // buffer(5)
+ /// Z – post-gate activations that modulate the residual output.
+ pub z: &'a MTLBuffer, // buffer(6)
+ /// Current state tensor.
+ pub state: &'a MTLBuffer, // buffer(7)
+ /// Y – residual output buffer.
+ pub y: &'a MTLBuffer, // buffer(8)
+ /// Next state tensor (same buffer as `state`, but written after update).
+ pub next_state: &'a MTLBuffer, // buffer(9)
+ pub batch_size: usize,
+ pub channels: usize,
+}
+
+impl SSMUpdateKernel {
+ pub fn new(
+ context: &MTLContext,
+ data_type: KernelDataType,
+ ) -> Result<Self, SSMKernelError> {
+ let fn_name = format!("ssm_update_kernel_{}", fn_suffix(data_type));
+ let pipeline = context
+ .compute_pipeline_state(&fn_name, None)
+ .map_err(SSMKernelError::MetalError)?;
+ Ok(Self {
+ pipeline,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ compute_encoder: &ComputeCommandEncoderRef,
+ args: SSMUpdateArguments,
+ ) -> Result<(), SSMKernelError> {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline);
+
+ compute_encoder.set_buffer(0, Some(args.x), 0);
+ compute_encoder.set_buffer(1, Some(args.dt), 0);
+ compute_encoder.set_buffer(2, Some(args.a), 0);
+ compute_encoder.set_buffer(3, Some(args.b), 0);
+ compute_encoder.set_buffer(4, Some(args.c), 0);
+ compute_encoder.set_buffer(5, Some(args.d), 0);
+ compute_encoder.set_buffer(6, Some(args.z), 0);
+ compute_encoder.set_buffer(7, Some(args.state), 0);
+ compute_encoder.set_buffer(8, Some(args.y), 0);
+ compute_encoder.set_buffer(9, Some(args.next_state), 0);
+
+ let threads_per_threadgroup = MTLSize {
+ width: 32,
+ height: 32,
+ depth: 1,
+ };
+ let total_threads = MTLSize {
+ width: args.batch_size as u64,
+ height: args.channels as u64,
+ depth: 1,
+ };
+ compute_encoder
+ .dispatch_threads(total_threads, threads_per_threadgroup);
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/mod.rs b/crates/uzu/src/backends/metal/mod.rs
index f6ea05d42..3f56dbd95 100644
--- a/crates/uzu/src/backends/metal/mod.rs
+++ b/crates/uzu/src/backends/metal/mod.rs
@@ -17,7 +17,7 @@ pub use buffer_allocator::BufferAllocator;
pub use context::MTLContext;
pub use error::MTLError;
pub use executable_builder::DecoderExecutables;
-pub use forward_pass::{ForwardPassState, KVCache, ModelShape};
+pub use forward_pass::{CacheLayers, ForwardPassState, ModelShape};
pub use kernel::{KVCacheUpdate, KernelDataType, RopeKernel};
// pub use kernel::{
// DataType as KernelDataType, Encoder as KernelEncoder,
diff --git a/crates/uzu/src/config/attention.rs b/crates/uzu/src/config/attention.rs
index a6245dedf..ca608ce81 100644
--- a/crates/uzu/src/config/attention.rs
+++ b/crates/uzu/src/config/attention.rs
@@ -10,8 +10,14 @@ pub struct AttentionConfig {
pub query_norm_config: Option<RMSNormConfig>,
pub key_norm_config: Option<RMSNormConfig>,
+ pub num_heads: Option<usize>,
+ pub num_groups: Option<usize>,
+ pub head_dim: Option<usize>,
+ pub is_causal: Option<bool>,
+ pub scale: Option<f32>,
+ pub sliding_window_size: Option<usize>,
+
pub logit_soft_cap: Option<f32>,
- #[serde(default)]
pub has_sinks: bool,
pub has_qkv_biases: bool,
pub has_out_biases: bool,
@@ -82,6 +88,12 @@ mod tests {
},
query_norm_config: None,
key_norm_config: None,
+ num_heads: None,
+ num_groups: None,
+ head_dim: None,
+ is_causal: None,
+ scale: None,
+ sliding_window_size: None,
logit_soft_cap: None,
has_sinks: false,
has_qkv_biases: false,
diff --git a/crates/uzu/src/config/common.rs b/crates/uzu/src/config/common.rs
index 228345efb..f99608cae 100644
--- a/crates/uzu/src/config/common.rs
+++ b/crates/uzu/src/config/common.rs
@@ -46,6 +46,24 @@ pub enum QuantizationMode {
UInt8,
}
+impl QuantizationMode {
+ pub fn packing_divisor(&self) -> usize {
+ match self {
+ QuantizationMode::UInt4 => 2,
+ QuantizationMode::Int8 => 1,
+ QuantizationMode::UInt8 => 1,
+ }
+ }
+
+ pub fn storage_type(&self) -> DataType {
+ match self {
+ QuantizationMode::UInt4 => DataType::U8,
+ QuantizationMode::Int8 => DataType::I8,
+ QuantizationMode::UInt8 => DataType::U8,
+ }
+ }
+}
+
impl Into<DataType> for QuantizationMode {
fn into(self) -> DataType {
match self {
@@ -60,12 +78,14 @@ impl Into<DataType> for QuantizationMode {
#[serde(tag = "type")]
pub enum Activation {
#[serde(rename = "SiLU")]
- SILU {
+ SiLU {
#[serde(default = "default_silu_alpha")]
alpha: f32,
},
#[serde(rename = "GELU")]
- GELU,
+ Gelu,
+ #[serde(rename = "Identity")]
+ Identity,
}
fn default_silu_alpha() -> f32 {
@@ -75,10 +95,11 @@ fn default_silu_alpha() -> f32 {
impl Activation {
pub fn alpha(&self) -> f32 {
match self {
- Activation::SILU {
+ Activation::SiLU {
alpha,
} => *alpha,
- Activation::GELU => 1.0,
+ Activation::Gelu => 1.0,
+ Activation::Identity => 1.0,
}
}
}
diff --git a/crates/uzu/src/config/decoder.rs b/crates/uzu/src/config/decoder.rs
index 34b0f36ec..8bf09a4f8 100644
--- a/crates/uzu/src/config/decoder.rs
+++ b/crates/uzu/src/config/decoder.rs
@@ -1,16 +1,37 @@
-use serde::{Deserialize, Serialize};
+use serde::{
+ Deserialize, Serialize,
+ de::{self, Deserializer},
+};
use super::{
- decoder_layer::DecoderLayerConfig, embedding::EmbeddingConfig,
- normalization::RMSNormConfig, rope::RoPEConfig,
+ decoder_layer::{DecoderLayerConfig, MixerConfig},
+ embedding::EmbeddingConfig,
+ normalization::RMSNormConfig,
+ rope::RoPEConfig,
};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum DecoderLayerType {
+ Transformer,
+ #[serde(rename = "ssm")]
+ StateSpace {
+ conv_dim: usize,
+ kernel_size: usize,
+ state_dim: usize,
+ num_heads: usize,
+ num_groups: usize,
+ head_dim: usize,
+ },
+}
+
+#[derive(Debug, Serialize, PartialEq, Clone)]
pub struct DecoderConfig {
pub embedding_config: EmbeddingConfig,
- pub global_rope_config: RoPEConfig,
+ pub global_rope_config: Option<RoPEConfig>,
pub local_rope_config: Option<RoPEConfig>,
pub layer_config: DecoderLayerConfig,
+ pub layer_configs: Option<Box<[DecoderLayerConfig]>>,
pub output_norm_config: RMSNormConfig,
pub vocab_size: usize,
@@ -22,9 +43,188 @@ pub struct DecoderConfig {
pub attention_scale: Option<f32>,
pub num_layers: usize,
pub sliding_window_sizes: Option<Box<[Option<usize>]>>,
+ pub layer_types: Option<Box<[DecoderLayerType]>>,
pub context_length: usize,
}
+impl<'de> Deserialize<'de> for DecoderConfig {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let raw = RawDecoderConfig::deserialize(deserializer)?;
+ let RawDecoderConfig {
+ embedding_config,
+ global_rope_config,
+ local_rope_config,
+ layer_config,
+ layer_configs,
+ output_norm_config,
+ vocab_size,
+ model_dim,
+ hidden_dim,
+ num_heads,
+ num_groups,
+ head_dim,
+ attention_scale,
+ num_layers,
+ sliding_window_sizes,
+ layer_types,
+ context_length,
+ } = raw;
+
+ let layer_configs_boxed =
+ layer_configs.map(|layers| layers.into_boxed_slice());
+
+ let layer_config_value = if let Some(config) = layer_config {
+ config
+ } else if let Some(configs) = layer_configs_boxed.as_ref() {
+ configs.first().cloned().ok_or_else(|| {
+ de::Error::custom("layer_configs must not be empty")
+ })?
+ } else {
+ return Err(de::Error::custom(
+ "decoder config must include layer_config or layer_configs",
+ ));
+ };
+
+ let num_layers_value = if let Some(value) = num_layers {
+ value
+ } else if let Some(configs) = layer_configs_boxed.as_ref() {
+ configs.len()
+ } else {
+ return Err(de::Error::custom(
+ "num_layers missing and layer_configs not provided",
+ ));
+ };
+
+ let (num_heads_value, num_groups_value, head_dim_value) =
+ match (num_heads, num_groups, head_dim) {
+ (Some(h), Some(g), Some(d)) => (h, g, d),
+ _ => derive_dims_from_layer(&layer_config_value).ok_or_else(
+ || {
+ de::Error::custom(
+ "num_heads/num_groups/head_dim missing and \
+ cannot be derived from layer config",
+ )
+ },
+ )?,
+ };
+
+ let attention_scale_value = if attention_scale.is_some() {
+ attention_scale
+ } else {
+ layer_config_value.mixer_config.attention_scale()
+ };
+
+ let sliding_window_sizes_boxed =
+ if let Some(sizes) = sliding_window_sizes {
+ Some(sizes.into_boxed_slice())
+ } else if let Some(configs) = layer_configs_boxed.as_ref() {
+ Some(
+ configs
+ .iter()
+ .map(|layer| layer.mixer_config.sliding_window_size())
+ .collect::<Vec<_>>()
+ .into_boxed_slice(),
+ )
+ } else {
+ None
+ };
+
+ let explicit_layer_types =
+ layer_types.map(|types| types.into_boxed_slice());
+ let derived_layer_types =
+ if let Some(configs) = layer_configs_boxed.as_ref() {
+ Some(
+ configs
+ .iter()
+ .map(layer_type_from_config)
+ .collect::<Vec<_>>()
+ .into_boxed_slice(),
+ )
+ } else {
+ None
+ };
+ let layer_types_value = explicit_layer_types.or(derived_layer_types);
+
+ Ok(Self {
+ embedding_config,
+ global_rope_config,
+ local_rope_config,
+ layer_config: layer_config_value,
+ layer_configs: layer_configs_boxed,
+ output_norm_config,
+ vocab_size,
+ model_dim,
+ hidden_dim,
+ num_heads: num_heads_value,
+ num_groups: num_groups_value,
+ head_dim: head_dim_value,
+ attention_scale: attention_scale_value,
+ num_layers: num_layers_value,
+ sliding_window_sizes: sliding_window_sizes_boxed,
+ layer_types: layer_types_value,
+ context_length,
+ })
+ }
+}
+
+#[derive(Deserialize)]
+struct RawDecoderConfig {
+ embedding_config: EmbeddingConfig,
+ #[serde(default)]
+ global_rope_config: Option<RoPEConfig>,
+ #[serde(default)]
+ local_rope_config: Option<RoPEConfig>,
+ #[serde(default)]
+ layer_config: Option<DecoderLayerConfig>,
+ #[serde(default)]
+ layer_configs: Option<Vec<DecoderLayerConfig>>,
+ output_norm_config: RMSNormConfig,
+ vocab_size: usize,
+ model_dim: usize,
+ hidden_dim: usize,
+ #[serde(default)]
+ num_heads: Option<usize>,
+ #[serde(default)]
+ num_groups: Option<usize>,
+ #[serde(default)]
+ head_dim: Option<usize>,
+ #[serde(default)]
+ attention_scale: Option<f32>,
+ #[serde(default)]
+ num_layers: Option<usize>,
+ #[serde(default)]
+ sliding_window_sizes: Option<Vec<Option<usize>>>,
+ #[serde(default)]
+ layer_types: Option<Vec<DecoderLayerType>>,
+ context_length: usize,
+}
+
+fn derive_dims_from_layer(
+ layer: &DecoderLayerConfig
+) -> Option<(usize, usize, usize)> {
+ Some((
+ layer.mixer_config.num_heads()?,
+ layer.mixer_config.num_groups()?,
+ layer.mixer_config.head_dim()?,
+ ))
+}
+
+fn layer_type_from_config(layer: &DecoderLayerConfig) -> DecoderLayerType {
+ match &layer.mixer_config {
+ MixerConfig::Attention(_) => DecoderLayerType::Transformer,
+ MixerConfig::Mamba(config) => DecoderLayerType::StateSpace {
+ conv_dim: config.conv_dim(),
+ kernel_size: config.kernel_size,
+ state_dim: config.state_dim,
+ num_heads: config.num_heads,
+ num_groups: config.num_groups,
+ head_dim: config.head_dim,
+ },
+ }
+}
impl DecoderConfig {
pub fn group_size(&self) -> usize {
self.num_heads * self.num_groups
@@ -79,7 +279,8 @@ mod tests {
"scale_offset": null,
"upcast_mode": "only_normalization"
},
- "attention_config": {
+ "mixer_config": {
+ "type": "AttentionConfig",
"qkv_projection_config": {
"type": "QLoRALinearConfig",
"group_size": 32,
@@ -87,7 +288,7 @@ mod tests {
"activation_quantization_mode": "int8",
"activation_precision": "bfloat16",
"lora_rank": 16,
- "lora_scale": 2.0,
+ "lora_scale": 2.0
},
"out_projection_config": {
"type": "QLoRALinearConfig",
@@ -96,10 +297,10 @@ mod tests {
"activation_quantization_mode": "int8",
"activation_precision": "bfloat16",
"lora_rank": 16,
- "lora_scale": 2.0,
+ "lora_scale": 2.0
},
"logit_soft_cap": null,
- "has_sinks": false,
+ "has_sinks": false,
"has_qkv_biases": false,
"has_out_biases": false
},
@@ -156,7 +357,7 @@ mod tests {
activation_quantization_mode: Some(QuantizationMode::Int8),
activation_precision: ConfigDataType::BFloat16,
},
- global_rope_config: RoPEConfig::Llama {
+ global_rope_config: Some(RoPEConfig::Llama {
common: RopeConfigCommon {
precision: ConfigDataType::BFloat16,
base: 500000.0,
@@ -166,7 +367,7 @@ mod tests {
original_context_length: 8192,
low_frequency_factor: 1.0,
high_frequency_factor: 4.0,
- },
+ }),
local_rope_config: None,
layer_config: DecoderLayerConfig {
pre_attention_norm_config: RMSNormConfig {
@@ -183,7 +384,7 @@ mod tests {
scale_offset: None,
upcast_mode: UpcastMode::OnlyNormalization,
},
- attention_config: AttentionConfig {
+ mixer_config: MixerConfig::Attention(AttentionConfig {
qkv_projection_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
group_size: 32,
@@ -210,11 +411,17 @@ mod tests {
},
query_norm_config: None,
key_norm_config: None,
+ num_heads: None,
+ num_groups: None,
+ head_dim: None,
+ is_causal: None,
+ scale: None,
+ sliding_window_size: None,
logit_soft_cap: None,
has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
- },
+ }),
mlp_config: MLPConfig::Dense(DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
@@ -228,7 +435,7 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU {
+ activation: Activation::SiLU {
alpha: 1.0,
},
}),
@@ -242,6 +449,7 @@ mod tests {
scale_offset: None,
upcast_mode: UpcastMode::OnlyNormalization,
},
+ layer_configs: None,
vocab_size: 128256,
model_dim: 2048,
hidden_dim: 8192,
@@ -251,10 +459,156 @@ mod tests {
attention_scale: None,
num_layers: 16,
sliding_window_sizes: None,
+ layer_types: None,
context_length: 8192,
};
let deserialized_config: DecoderConfig = from_str(config_str).unwrap();
assert_eq!(deserialized_config, ground_truth_config);
}
+
+ #[test]
+ fn test_decoder_config_with_layer_configs() {
+ let config_str = r#"
+ {
+ "embedding_config": {
+ "type": "TiedEmbeddingConfig",
+ "input_scale": null,
+ "logit_soft_cap": null,
+ "precision": "bfloat16"
+ },
+ "global_rope_config": null,
+ "local_rope_config": null,
+ "layer_configs": [
+ {
+ "pre_mixer_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mixer_config": {
+ "type": "AttentionConfig",
+ "qkv_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "out_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "query_norm_config": null,
+ "key_norm_config": null,
+ "num_heads": 4,
+ "num_groups": 1,
+ "head_dim": 256,
+ "is_causal": true,
+ "scale": 0.0625,
+ "sliding_window_size": 512,
+ "logit_soft_cap": null,
+ "has_sinks": false,
+ "has_qkv_biases": false,
+ "has_out_biases": false
+ },
+ "post_mixer_norm_config": null,
+ "pre_mlp_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mlp_config": {
+ "type": "DenseMLPConfig",
+ "linear_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "activation": {
+ "type": "GELU"
+ }
+ },
+ "post_mlp_norm_config": null
+ },
+ {
+ "pre_mixer_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mixer_config": {
+ "type": "AttentionConfig",
+ "qkv_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "out_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "query_norm_config": null,
+ "key_norm_config": null,
+ "num_heads": 4,
+ "num_groups": 1,
+ "head_dim": 256,
+ "is_causal": true,
+ "scale": 0.0625,
+ "sliding_window_size": 256,
+ "logit_soft_cap": null,
+ "has_sinks": false,
+ "has_qkv_biases": false,
+ "has_out_biases": false
+ },
+ "post_mixer_norm_config": null,
+ "pre_mlp_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mlp_config": {
+ "type": "DenseMLPConfig",
+ "linear_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "activation": {
+ "type": "GELU"
+ }
+ },
+ "post_mlp_norm_config": null
+ }
+ ],
+ "output_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "vocab_size": 32000,
+ "model_dim": 1152,
+ "hidden_dim": 6912,
+ "context_length": 32768
+ }
+ "#;
+
+ let config: DecoderConfig = from_str(config_str).unwrap();
+ assert_eq!(config.num_layers, 2);
+ assert_eq!(config.num_heads, 4);
+ assert_eq!(config.num_groups, 1);
+ assert_eq!(config.head_dim, 256);
+ assert_eq!(config.attention_scale, Some(0.0625));
+ let sliding_windows = config.sliding_window_sizes.unwrap();
+ assert_eq!(sliding_windows.len(), 2);
+ assert_eq!(sliding_windows[0], Some(512));
+ assert_eq!(sliding_windows[1], Some(256));
+ let layer_types = config.layer_types.unwrap();
+ assert!(matches!(layer_types[0], DecoderLayerType::Transformer));
+ assert_eq!(config.layer_configs.unwrap().len(), 2);
+ }
}
diff --git a/crates/uzu/src/config/decoder_layer.rs b/crates/uzu/src/config/decoder_layer.rs
index 2f65467d8..be78c548e 100644
--- a/crates/uzu/src/config/decoder_layer.rs
+++ b/crates/uzu/src/config/decoder_layer.rs
@@ -1,19 +1,91 @@
use serde::{Deserialize, Serialize};
use super::{
- attention::AttentionConfig, mlp::MLPConfig, normalization::RMSNormConfig,
+ attention::AttentionConfig, mamba::Mamba2Config, mlp::MLPConfig,
+ normalization::RMSNormConfig,
};
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+#[serde(tag = "type")]
+pub enum MixerConfig {
+ #[serde(rename = "AttentionConfig")]
+ Attention(AttentionConfig),
+ #[serde(rename = "Mamba2Config")]
+ Mamba(Mamba2Config),
+}
+
+impl MixerConfig {
+ pub fn as_attention(&self) -> Option<&AttentionConfig> {
+ match self {
+ MixerConfig::Attention(config) => Some(config),
+ _ => None,
+ }
+ }
+
+ pub fn as_mamba(&self) -> Option<&Mamba2Config> {
+ match self {
+ MixerConfig::Mamba(config) => Some(config),
+ _ => None,
+ }
+ }
+
+ pub fn num_heads(&self) -> Option<usize> {
+ match self {
+ MixerConfig::Attention(config) => config.num_heads,
+ MixerConfig::Mamba(config) => Some(config.num_heads),
+ }
+ }
+
+ pub fn num_groups(&self) -> Option<usize> {
+ match self {
+ MixerConfig::Attention(config) => config.num_groups,
+ MixerConfig::Mamba(config) => Some(config.num_groups),
+ }
+ }
+
+ pub fn head_dim(&self) -> Option<usize> {
+ match self {
+ MixerConfig::Attention(config) => config.head_dim,
+ MixerConfig::Mamba(config) => Some(config.head_dim),
+ }
+ }
+
+ pub fn sliding_window_size(&self) -> Option<usize> {
+ match self {
+ MixerConfig::Attention(config) => config.sliding_window_size,
+ MixerConfig::Mamba(_) => None,
+ }
+ }
+
+ pub fn attention_scale(&self) -> Option<f32> {
+ match self {
+ MixerConfig::Attention(config) => config.scale,
+ MixerConfig::Mamba(_) => None,
+ }
+ }
+}
+
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct DecoderLayerConfig {
+ #[serde(alias = "pre_mixer_norm_config")]
pub pre_attention_norm_config: RMSNormConfig,
- pub attention_config: AttentionConfig,
+ #[serde(alias = "mixer_config")]
+ pub mixer_config: MixerConfig,
+ #[serde(alias = "post_mixer_norm_config")]
pub post_attention_norm_config: Option<RMSNormConfig>,
+ #[serde(alias = "pre_mlp_norm_config")]
pub pre_mlp_norm_config: RMSNormConfig,
pub mlp_config: MLPConfig,
+ #[serde(alias = "post_mlp_norm_config")]
pub post_mlp_norm_config: Option<RMSNormConfig>,
}
+impl DecoderLayerConfig {
+ pub fn attention_config(&self) -> Option<&AttentionConfig> {
+ self.mixer_config.as_attention()
+ }
+}
+
#[cfg(test)]
mod tests {
use serde_json::from_str;
@@ -39,7 +111,8 @@ mod tests {
"scale_offset": null,
"upcast_mode": "only_normalization"
},
- "attention_config": {
+ "mixer_config": {
+ "type": "AttentionConfig",
"qkv_projection_config": {
"type": "QLoRALinearConfig",
"group_size": 32,
@@ -103,7 +176,7 @@ mod tests {
scale_offset: None,
upcast_mode: UpcastMode::OnlyNormalization,
},
- attention_config: AttentionConfig {
+ mixer_config: MixerConfig::Attention(AttentionConfig {
qkv_projection_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
group_size: 32,
@@ -134,7 +207,13 @@ mod tests {
has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
- },
+ num_heads: None,
+ num_groups: None,
+ head_dim: None,
+ is_causal: None,
+ scale: None,
+ sliding_window_size: None,
+ }),
mlp_config: MLPConfig::Dense(mlp::DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
@@ -148,7 +227,7 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU {
+ activation: Activation::SiLU {
alpha: 1.0,
},
}),
diff --git a/crates/uzu/src/config/embedding.rs b/crates/uzu/src/config/embedding.rs
index 092ecc276..5a7bcb90c 100644
--- a/crates/uzu/src/config/embedding.rs
+++ b/crates/uzu/src/config/embedding.rs
@@ -31,6 +31,24 @@ pub enum EmbeddingConfig {
activation_quantization_mode: Option<QuantizationMode>,
activation_precision: ConfigDataType,
},
+ #[serde(rename = "MLXQuantizedTiedEmbeddingConfig")]
+ MLXQuantizedTied {
+ #[serde(flatten)]
+ common: EmbeddingConfigCommon,
+ group_size: usize,
+ embedding_quantization_mode: QuantizationMode,
+ activation_quantization_mode: Option<QuantizationMode>,
+ activation_precision: ConfigDataType,
+ },
+ #[serde(rename = "MLXSemiQuantizedUntiedEmbeddingConfig")]
+ MLXSemiQuantizedUntied {
+ #[serde(flatten)]
+ common: EmbeddingConfigCommon,
+ group_size: usize,
+ embedding_quantization_mode: QuantizationMode,
+ activation_quantization_mode: Option<QuantizationMode>,
+ activation_precision: ConfigDataType,
+ },
}
impl EmbeddingConfig {
@@ -48,6 +66,14 @@ impl EmbeddingConfig {
common,
..
} => common,
+ EmbeddingConfig::MLXQuantizedTied {
+ common,
+ ..
+ } => common,
+ EmbeddingConfig::MLXSemiQuantizedUntied {
+ common,
+ ..
+ } => common,
}
}
}
@@ -84,5 +110,31 @@ mod tests {
let deserialized_config: EmbeddingConfig =
from_str(config_str).unwrap();
assert_eq!(deserialized_config, ground_truth_config);
+
+ let semi_config_str = r#"
+ {
+ "type": "MLXSemiQuantizedUntiedEmbeddingConfig",
+ "input_scale": null,
+ "logit_soft_cap": null,
+ "group_size": 128,
+ "embedding_quantization_mode": "uint4",
+ "activation_quantization_mode": null,
+ "activation_precision": "bfloat16"
+ }
+ "#;
+
+ let semi_config = EmbeddingConfig::MLXSemiQuantizedUntied {
+ common: EmbeddingConfigCommon {
+ input_scale: None,
+ logit_soft_cap: None,
+ },
+ group_size: 128,
+ embedding_quantization_mode: QuantizationMode::UInt4,
+ activation_quantization_mode: None,
+ activation_precision: ConfigDataType::BFloat16,
+ };
+
+ let deserialized: EmbeddingConfig = from_str(semi_config_str).unwrap();
+ assert_eq!(deserialized, semi_config);
}
}
diff --git a/crates/uzu/src/config/linear.rs b/crates/uzu/src/config/linear.rs
index 34712aa8d..49bd4ecab 100644
--- a/crates/uzu/src/config/linear.rs
+++ b/crates/uzu/src/config/linear.rs
@@ -19,6 +19,8 @@ pub enum LinearConfig {
},
#[serde(rename = "GroupQuantizedLinearConfig")]
Quantized(QuantizationConfig),
+ #[serde(rename = "MLXQuantizedLinearConfig")]
+ MLXQuantized(QuantizationConfig),
#[serde(rename = "QLoRALinearConfig")]
QLoRA {
#[serde(flatten)]
@@ -37,6 +39,9 @@ impl LinearConfig {
LinearConfig::Quantized(quantization) => {
quantization.activation_precision
},
+ LinearConfig::MLXQuantized(quantization) => {
+ quantization.activation_precision
+ },
LinearConfig::QLoRA {
quantization,
..
diff --git a/crates/uzu/src/config/mamba.rs b/crates/uzu/src/config/mamba.rs
new file mode 100644
index 000000000..055dc3c45
--- /dev/null
+++ b/crates/uzu/src/config/mamba.rs
@@ -0,0 +1,38 @@
+use serde::{Deserialize, Serialize};
+
+use super::{
+ common::{Activation, ConfigDataType},
+ linear::LinearConfig,
+};
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct CausalConv1dConfig {
+ pub precision: ConfigDataType,
+ pub has_biases: bool,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct Mamba2Config {
+ pub in_projection_config: LinearConfig,
+ pub out_projection_config: LinearConfig,
+ pub conv_config: CausalConv1dConfig,
+ pub activation: Activation,
+ pub kernel_size: usize,
+ pub num_heads: usize,
+ pub num_groups: usize,
+ pub head_dim: usize,
+ pub state_dim: usize,
+ pub expansion_factor: usize,
+ pub has_in_biases: bool,
+ pub has_out_biases: bool,
+}
+
+impl Mamba2Config {
+ pub fn inner_dim(&self) -> usize {
+ self.num_heads * self.head_dim
+ }
+
+ pub fn conv_dim(&self) -> usize {
+ self.inner_dim() + 2 * self.num_groups * self.state_dim
+ }
+}
diff --git a/crates/uzu/src/config/mlp.rs b/crates/uzu/src/config/mlp.rs
index 637e625dc..fa9832b44 100644
--- a/crates/uzu/src/config/mlp.rs
+++ b/crates/uzu/src/config/mlp.rs
@@ -80,7 +80,7 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU {
+ activation: Activation::SiLU {
alpha: 1.0,
},
});
@@ -140,7 +140,7 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU {
+ activation: Activation::SiLU {
alpha: 1.0,
},
has_up_biases: true,
diff --git a/crates/uzu/src/config/mod.rs b/crates/uzu/src/config/mod.rs
index 9671b6ad8..c08e0df97 100644
--- a/crates/uzu/src/config/mod.rs
+++ b/crates/uzu/src/config/mod.rs
@@ -14,6 +14,8 @@ pub mod mlp;
pub use mlp::*;
pub mod normalization;
pub use normalization::*;
+pub mod mamba;
+pub use mamba::*;
pub mod rope;
pub use rope::*;
pub mod metadata;
diff --git a/crates/uzu/src/generator/context.rs b/crates/uzu/src/generator/context.rs
index 8d1282e0a..b8d6e3fcc 100644
--- a/crates/uzu/src/generator/context.rs
+++ b/crates/uzu/src/generator/context.rs
@@ -6,8 +6,8 @@ use objc2::rc::Retained;
use crate::{
DataType,
backends::metal::{
- DecoderExecutables, KVCache, KVCacheUpdate, KernelDataType, MTLContext,
- ModelShape,
+ CacheLayers, DecoderExecutables, KVCacheUpdate, KernelDataType,
+ MTLContext, ModelShape,
compilation_parameters::CompilationConfig,
forward_pass::{ForwardPassBuffers, SharedBuffers},
kernel::SamplingKernelEncodable,
@@ -26,7 +26,7 @@ pub struct GeneratorContext {
pub mtl_context: Rc<MTLContext>,
pub command_buffer: Retained<MPSCommandBuffer>,
- pub kv_cache: Rc<RefCell<KVCache>>,
+ pub cache_layers: Rc<RefCell<CacheLayers>>,
pub shared_buffers: Rc<RefCell<SharedBuffers>>,
pub scratch_buffers: ForwardPassBuffers,
@@ -112,7 +112,7 @@ impl GeneratorContext {
compilation_config.clone(),
);
- let kv_cache = Rc::new(RefCell::new(KVCache::new(
+ let cache_layers = Rc::new(RefCell::new(CacheLayers::new(
&mtl_context,
&model_shape,
max_prefix_length,
@@ -145,7 +145,7 @@ impl GeneratorContext {
let context = Self {
mtl_context,
command_buffer,
- kv_cache,
+ cache_layers,
shared_buffers,
scratch_buffers,
model_config: model_metadata.model_config.clone(),
diff --git a/crates/uzu/src/generator/generator.rs b/crates/uzu/src/generator/generator.rs
index d1ddcf0b9..3bea1cf9d 100644
--- a/crates/uzu/src/generator/generator.rs
+++ b/crates/uzu/src/generator/generator.rs
@@ -11,9 +11,8 @@ use super::{
use crate::{
Array,
backends::metal::forward_pass::{
- ForwardPassState,
+ ForwardPassState, INVALID_POSITION,
encodable_with_state::{EncodableWithState, EncodingParameters},
- kv_cache::INVALID_POSITION,
},
linearizer::trie::{TokenTrie, TrieCreationConfig},
session::{
@@ -140,8 +139,15 @@ impl Generator {
&padded_tokens[tokens_start_index..tokens_end_index];
let positions_for_step =
&padded_positions[tokens_start_index..tokens_end_index];
+ let active_suffix_length = positions_for_step
+ .iter()
+ .position(|&pos| pos == INVALID_POSITION)
+ .unwrap_or(prefill_step_size);
let seeds_for_step =
&padded_seeds[tokens_start_index..tokens_end_index];
+ let is_last_prefill_step = step == number_of_prefill_steps - 1;
+ let should_sample_after_step =
+ sample_suffix && is_last_prefill_step;
let is_first_prefill = step == 0;
let should_capture =
@@ -162,6 +168,8 @@ impl Generator {
token_positions: positions_for_step.to_vec(),
token_seeds: seeds_for_step.to_vec(),
expected_number_of_new_tokens: prefill_step_size,
+ active_suffix_length,
+ is_prefilling: !should_sample_after_step,
};
let (state, run_time) = self.run_model(
@@ -196,7 +204,7 @@ impl Generator {
let accept_indices_for_step: Vec<usize> =
(0..positions_for_step.len()).collect();
if !accept_indices_for_step.is_empty() {
- self.update_kv_cache(
+ self.update_cache_layers(
&accept_indices_for_step,
None,
true,
@@ -204,7 +212,7 @@ impl Generator {
}
self.context
- .kv_cache
+ .cache_layers
.borrow_mut()
.register_accepted_tokens(&positions_for_step);
@@ -256,7 +264,7 @@ impl Generator {
}
}
- self.update_kv_cache(
+ self.update_cache_layers(
&accepted_token_indices,
Some(last_suffix_start),
false,
@@ -310,12 +318,15 @@ impl Generator {
std::iter::repeat(INVALID_POSITION).take(unused_tokens_count),
)
.collect();
+ let active_suffix_length = speculated_suffix.tokens.len();
let task = GeneratorRunTask {
token_ids: padded_tokens,
token_positions: padded_positions,
token_seeds: padded_seeds,
expected_number_of_new_tokens: 1,
+ active_suffix_length,
+ is_prefilling: false,
};
let (mut state, run_time) = self.run_model(
@@ -347,7 +358,7 @@ impl Generator {
}
}
- self.update_kv_cache(&accepted_token_indices, None, false);
+ self.update_cache_layers(&accepted_token_indices, None, false);
self.tokens.extend(accepted_tokens.clone());
self.sync_prefix();
@@ -365,7 +376,7 @@ impl Generator {
}
pub fn reset_state(&mut self) {
- self.context.kv_cache.borrow_mut().clear();
+ self.context.cache_layers.borrow_mut().clear();
self.tokens.clear();
self.registered_prefix_len = 0;
self.encoded_tasks.clear();
@@ -385,6 +396,8 @@ impl Generator {
token_positions: (0..suffix_length).collect::<Vec<usize>>(),
token_seeds: vec![0; suffix_length],
expected_number_of_new_tokens: suffix_length,
+ active_suffix_length: suffix_length,
+ is_prefilling: false,
};
let (_, _) =
@@ -437,11 +450,13 @@ impl Generator {
self.context.command_buffer.root_command_buffer().to_owned();
if !warmup {
- self.context.gpu_sampler.encode(
- &mut state,
- &self.context.command_buffer,
- &EncodingParameters::new(warmup, true, false),
- );
+ if !task.is_prefilling {
+ self.context.gpu_sampler.encode(
+ &mut state,
+ &self.context.command_buffer,
+ &EncodingParameters::new(warmup, true, false),
+ );
+ }
}
self.context.command_buffer.commit_and_continue();
@@ -494,7 +509,7 @@ impl Generator {
Ok(result)
}
- fn update_kv_cache(
+ fn update_cache_layers(
&mut self,
accepted_token_indices: &[usize],
suffix_start: Option<usize>,
@@ -507,8 +522,8 @@ impl Generator {
command_buffer.root_command_buffer().to_owned();
{
- let mut kv_cache = self.context.kv_cache.borrow_mut();
- kv_cache.update_after_acceptance(
+ let mut cache_layers = self.context.cache_layers.borrow_mut();
+ cache_layers.update_after_acceptance(
accepted_token_indices,
suffix_start,
&root_command_buffer,
@@ -543,7 +558,7 @@ impl Generator {
(self.registered_prefix_len..desired_prefix_len).collect();
if !positions.is_empty() {
self.context
- .kv_cache
+ .cache_layers
.borrow_mut()
.register_accepted_tokens(&positions);
}
diff --git a/crates/uzu/src/generator/tasks.rs b/crates/uzu/src/generator/tasks.rs
index 0365df800..a04cdbda0 100644
--- a/crates/uzu/src/generator/tasks.rs
+++ b/crates/uzu/src/generator/tasks.rs
@@ -16,6 +16,8 @@ pub struct GeneratorRunTask {
pub token_positions: Vec<usize>,
pub token_seeds: Vec<u64>,
pub expected_number_of_new_tokens: usize,
+ pub active_suffix_length: usize,
+ pub is_prefilling: bool,
}
impl GeneratorRunTask {
@@ -25,6 +27,8 @@ impl GeneratorRunTask {
token_positions: self.token_positions.clone(),
token_seeds: self.token_seeds.clone(),
expected_number_of_new_tokens: self.expected_number_of_new_tokens,
+ active_suffix_length: self.active_suffix_length,
+ is_prefilling: self.is_prefilling,
}
}
@@ -48,10 +52,12 @@ impl GeneratorRunTask {
&context.model_config.decoder_config,
&context.model_shape,
&context.scratch_buffers,
- context.kv_cache.clone(),
+ context.cache_layers.clone(),
context.shared_buffers.clone(),
&self.token_ids,
&self.token_positions,
+ self.active_suffix_length,
+ self.is_prefilling,
&self.token_seeds,
false,
external_bias_fn,
diff --git a/crates/uzu/src/runners/decoder_runner.rs b/crates/uzu/src/runners/decoder_runner.rs
index 9b8693ff3..34b77814b 100644
--- a/crates/uzu/src/runners/decoder_runner.rs
+++ b/crates/uzu/src/runners/decoder_runner.rs
@@ -8,7 +8,8 @@ use serde::{Deserialize, Serialize};
use crate::{
backends::metal::{
- DecoderExecutables, ForwardPassState, KVCache, MTLContext, ModelShape,
+ CacheLayers, DecoderExecutables, ForwardPassState, MTLContext,
+ ModelShape,
compilation_parameters::CompilationConfig,
forward_pass::{
ForwardPassBuffers, SharedBuffers,
@@ -91,7 +92,7 @@ impl DecoderTestContext {
.map_err(|e| format!("Failed to create ParameterLoader: {}", e))?;
let root_loader_view = loader.tree();
- let kv_cache = Rc::new(RefCell::new(KVCache::new(
+ let cache_layers = Rc::new(RefCell::new(CacheLayers::new(
&mtl_context,
&model_shape,
max_prefix_length,
@@ -122,10 +123,12 @@ impl DecoderTestContext {
&decoder_config,
&model_shape,
&scratch_buffers,
- kv_cache.clone(),
+ cache_layers.clone(),
shared_buffers.clone(),
&token_ids,
&token_positions,
+ token_ids.len(),
+ false,
&token_seeds,
false,
None,
diff --git a/crates/uzu/src/session/helpers/context.rs b/crates/uzu/src/session/helpers/context.rs
index cb2b91ba4..532ff8de3 100644
--- a/crates/uzu/src/session/helpers/context.rs
+++ b/crates/uzu/src/session/helpers/context.rs
@@ -1,23 +1,23 @@
use crate::{
- backends::metal::forward_pass::kv_cache::KVCache,
+ backends::metal::forward_pass::cache_layers::CacheLayers,
session::config::DecodingConfig,
};
pub struct Context {
pub tokens: Vec<u64>,
- pub kv_cache: KVCache,
+ pub cache_layers: CacheLayers,
pub decoding_config: DecodingConfig,
}
impl Context {
pub fn new(
tokens: Vec<u64>,
- kv_cache: KVCache,
+ cache_layers: CacheLayers,
decoding_config: DecodingConfig,
) -> Self {
Self {
tokens,
- kv_cache,
+ cache_layers,
decoding_config,
}
}
diff --git a/crates/uzu/src/session/session.rs b/crates/uzu/src/session/session.rs
index 16d1043fd..4990a8cc2 100644
--- a/crates/uzu/src/session/session.rs
+++ b/crates/uzu/src/session/session.rs
@@ -4,7 +4,8 @@ use objc2::rc::autoreleasepool;
use tokenizers::Tokenizer;
use crate::{
- config::ModelMetadata,
+ backends::metal::forward_pass::cache_layers::CacheLayer,
+ config::{ModelMetadata, decoder_layer::MixerConfig},
generator::{
generator::Generator,
result::{GenerateResult, PrefillResult},
@@ -53,9 +54,35 @@ impl Session {
}
let config_file =
File::open(&config_path).map_err(|_| Error::UnableToLoadConfig)?;
- let model_metadata: ModelMetadata =
- serde_json::from_reader(BufReader::new(config_file))
- .map_err(|_| Error::UnableToLoadConfig)?;
+ let model_metadata: ModelMetadata = serde_json::from_reader(
+ BufReader::new(config_file),
+ )
+ .map_err(|err| {
+ eprintln!("Failed to parse config.json: {err}");
+ Error::UnableToLoadConfig
+ })?;
+
+ let is_ssm = model_metadata
+ .clone()
+ .model_config
+ .decoder_config
+ .layer_configs
+ .unwrap_or(Box::new([]))
+ .iter()
+ .any(|layer| matches!(layer.mixer_config, MixerConfig::Mamba(_)));
+ if is_ssm {
+ match decoding_config.context_mode {
+ ContextMode::None => {},
+ ContextMode::Static {
+ ..
+ } => {
+ return Err(Error::UnsupportedContextModeForModel);
+ },
+ ContextMode::Dynamic => {
+ return Err(Error::UnsupportedContextModeForModel);
+ },
+ }
+ }
let tokenizer_path = model_path.join("tokenizer.json");
if !tokenizer_path.exists() {
@@ -173,44 +200,6 @@ impl Session {
Ok((output, new_context))
}
- fn reconfigure_generator(
- &mut self,
- context: Option<&Context>,
- ) -> Result<(), Error> {
- let generator =
- self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;
- generator.reset_state();
- if let Some(ctx) = context {
- let mut generator_cache = generator.context.kv_cache.borrow_mut();
- for (ctx_layer, gen_layer) in
- ctx.kv_cache.data.iter().zip(generator_cache.data.iter_mut())
- {
- let copy_rows = ctx_layer.prefix_segment_length();
- if copy_rows > 0 {
- gen_layer.keys.borrow_mut().copy_slice(
- &ctx_layer.keys.borrow(),
- 1,
- 0..copy_rows,
- 0,
- );
- gen_layer.values.borrow_mut().copy_slice(
- &ctx_layer.values.borrow(),
- 1,
- 0..copy_rows,
- 0,
- );
- }
- gen_layer.state = ctx_layer.state.clone();
- gen_layer.prefix_token_positions =
- ctx_layer.prefix_token_positions.clone();
- }
- drop(generator_cache);
-
- generator.tokens = ctx.tokens.clone();
- }
- Ok(())
- }
-
fn run_internal<F>(
&mut self,
input: Input,
@@ -321,6 +310,7 @@ impl Session {
let prefill_output = Output {
text: prefill_parsed_text,
stats: Self::build_stats(
+ &self.model_metadata,
prefill_result.clone(),
prefill_duration,
prefill_suffix_length,
@@ -369,6 +359,7 @@ impl Session {
let generate_output = Output {
text: generate_parsed_text,
stats: Self::build_stats(
+ &self.model_metadata,
prefill_result.clone(),
prefill_duration,
prefill_suffix_length,
@@ -404,17 +395,92 @@ impl Session {
.clone_with_duration(run_start.elapsed().as_secs_f64()))
}
+ fn reconfigure_generator(
+ &mut self,
+ context: Option<&Context>,
+ ) -> Result<(), Error> {
+ let generator =
+ self.generator.as_mut().ok_or(Error::GeneratorNotLoaded)?;
+ generator.reset_state();
+ if let Some(ctx) = context {
+ let mut generator_state =
+ generator.context.cache_layers.borrow_mut();
+ for (ctx_layer, gen_layer) in ctx
+ .cache_layers
+ .data
+ .iter()
+ .zip(generator_state.data.iter_mut())
+ {
+ match (ctx_layer, gen_layer) {
+ (
+ CacheLayer::Transformer(src),
+ CacheLayer::Transformer(dst),
+ ) => {
+ let copy_rows = src.prefix_segment_length();
+ if copy_rows > 0 {
+ {
+ let mut dst_keys = dst.keys.borrow_mut();
+ let src_keys = src.keys.borrow();
+ dst_keys.copy_slice(
+ &src_keys,
+ 1,
+ 0..copy_rows,
+ 0,
+ );
+ }
+ {
+ let mut dst_values = dst.values.borrow_mut();
+ let src_values = src.values.borrow();
+ dst_values.copy_slice(
+ &src_values,
+ 1,
+ 0..copy_rows,
+ 0,
+ );
+ }
+ }
+ dst.state = src.state.clone();
+ dst.prefix_token_positions =
+ src.prefix_token_positions.clone();
+ },
+ (
+ CacheLayer::StateSpace(src),
+ CacheLayer::StateSpace(dst),
+ ) => {
+ {
+ let mut dst_conv = dst.conv_state.borrow_mut();
+ let src_conv = src.conv_state.borrow();
+ dst_conv.copy_from_array(&src_conv);
+ }
+ {
+ let mut dst_ssm = dst.ssm_state.borrow_mut();
+ let src_ssm = src.ssm_state.borrow();
+ dst_ssm.copy_from_array(&src_ssm);
+ }
+ },
+ _ => panic!(
+ "Layer type mismatch when reconfiguring generator cache"
+ ),
+ }
+ }
+ drop(generator_state);
+
+ generator.tokens = ctx.tokens.clone();
+ }
+ Ok(())
+ }
+
fn build_context_from_generator(&self) -> Result<Context, Error> {
let generator =
self.generator.as_ref().ok_or(Error::GeneratorNotLoaded)?;
- let kv_cache = generator
+ let cache_layers = generator
.context
- .kv_cache
+ .cache_layers
.borrow()
.clone(&generator.context.mtl_context);
let context = Context::new(
generator.tokens.clone(),
- kv_cache,
+ cache_layers,
generator.decoding_config.clone(),
);
Ok(context)
@@ -423,6 +489,7 @@ impl Session {
impl Session {
fn build_stats(
+ model_metadata: &ModelMetadata,
prefill_result: PrefillResult,
prefill_duration: f64,
prefill_suffix_length: usize,
@@ -436,7 +503,19 @@ impl Session {
let prefill_stats = {
let tokens_count = prefill_result.tokens.len();
let tokens_per_second = tokens_count as f64 / prefill_duration;
- let processed_tokens = tokens_count_input + tokens_count;
+
+ // TODO: Unify after removing MPS blocks
+ let processed_tokens = if model_metadata.quantization.is_some() {
+ let result = tokens_count_input + tokens_count;
+ result
+ } else {
+ let number_of_prefill_steps =
+ (tokens_count_input as f32 / prefill_suffix_length as f32)
+ .ceil() as usize;
+ let result = prefill_suffix_length * number_of_prefill_steps
+ + tokens_count;
+ result
+ };
let processed_tokens_per_second =
processed_tokens as f64 / prefill_duration;
diff --git a/crates/uzu/src/session/types/error.rs b/crates/uzu/src/session/types/error.rs
index 3154c7298..a3905a09c 100644
--- a/crates/uzu/src/session/types/error.rs
+++ b/crates/uzu/src/session/types/error.rs
@@ -12,6 +12,8 @@ pub enum Error {
UnableToLoadTokenizer,
#[error("Model is too large to fit into available RAM")]
NotEnoughMemory,
+ #[error("Unsupported context mode for model")]
+ UnsupportedContextModeForModel,
#[error("Generator not loaded")]
GeneratorNotLoaded,
#[error("Unable to load prompt template")]
diff --git a/crates/uzu/src/tracer/tracer.rs b/crates/uzu/src/tracer/tracer.rs
index 7caec808f..ec284ceb7 100644
--- a/crates/uzu/src/tracer/tracer.rs
+++ b/crates/uzu/src/tracer/tracer.rs
@@ -12,8 +12,8 @@ use num_traits::NumCast;
use crate::{
Array, ArrayElement, DataType,
backends::metal::{
- ForwardPassState, KVCache, KVCacheUpdate, KernelDataType, MTLContext,
- MetalArray,
+ CacheLayers, ForwardPassState, KVCacheUpdate, KernelDataType,
+ MTLContext, MetalArray,
forward_pass::{
ArrayId, ForwardPassBuffers,
encodable_with_state::{EncodableWithState, EncodingParameters},
@@ -37,6 +37,7 @@ use crate::{
enum Transform {
KVCacheSlice,
+ SsmConvState,
}
pub struct TracerValidationMetrics {
@@ -249,7 +250,7 @@ impl Tracer {
desired_suffix_length,
);
- context.kv_cache = Rc::new(RefCell::new(KVCache::new(
+ context.cache_layers = Rc::new(RefCell::new(CacheLayers::new(
&context.mtl_context,
&context.model_shape,
resolved_prefix_length,
@@ -308,10 +309,12 @@ impl Tracer {
&self.generator_context.model_config.decoder_config,
&self.generator_context.model_shape,
&self.generator_context.scratch_buffers,
- self.generator_context.kv_cache.clone(),
+ self.generator_context.cache_layers.clone(),
self.generator_context.shared_buffers.clone(),
&token_ids,
&token_positions,
+ token_ids.len(),
+ false,
&token_seeds,
true,
None,
@@ -353,17 +356,25 @@ impl Tracer {
|expected_array_path: &str,
produced_array: &Ref<MetalArray>,
produced_transform: Option<Transform>| {
- let metrics = Self::validate_array_with_name(
- data_type,
- traces_view,
- expected_array_path.to_string(),
- produced_array,
- produced_transform,
- );
- results.push(TracerValidationResult {
- name: expected_array_path.to_string(),
- metrics,
- });
+ if let Ok(expected_array) =
+ traces_view.leaf(expected_array_path)
+ {
+ let metrics = Self::validate_array(
+ data_type,
+ &expected_array,
+ produced_array,
+ produced_transform,
+ );
+ results.push(TracerValidationResult {
+ name: expected_array_path.to_string(),
+ metrics,
+ });
+ } else {
+ println!(
+ "Warning: Trace key not found: {}",
+ expected_array_path
+ );
+ }
};
for (index, layer_traces) in
@@ -383,12 +394,12 @@ impl Tracer {
None,
);
validate(
- path("pre_attention_norm").as_str(),
+ path("pre_mixer_norm").as_str(),
&layer_traces.borrow().pre_attention_norm.borrow(),
None,
);
validate(
- path("attention").as_str(),
+ path("mixer").as_str(),
&layer_traces.borrow().attention.borrow(),
None,
);
@@ -397,7 +408,7 @@ impl Tracer {
.is_some()
{
validate(
- path("post_attention_norm").as_str(),
+ path("post_mixer_norm").as_str(),
&layer_traces.borrow().post_attention_norm.borrow(),
None,
);
@@ -445,7 +456,19 @@ impl Tracer {
);
validate("logits", &traces.borrow().logits.borrow(), None);
- for index in 0..state.kv_cache.borrow().data.len() {
+ let transformer_layers: Vec<usize> = {
+ let cache = state.cache_layers.borrow();
+ cache
+ .data
+ .iter()
+ .enumerate()
+ .filter_map(|(index, layer)| {
+ layer.as_transformer().map(|_| index)
+ })
+ .collect()
+ };
+
+ for index in transformer_layers {
let arrays =
state.arrays(&[ArrayId::Keys(index), ArrayId::Values(index)]);
@@ -464,6 +487,57 @@ impl Tracer {
);
}
+ let ssm_layers: Vec<usize> = {
+ let cache = state.cache_layers.borrow();
+ cache
+ .data
+ .iter()
+ .enumerate()
+ .filter_map(|(index, layer)| {
+ layer.as_state_space().map(|_| index)
+ })
+ .collect()
+ };
+
+ for index in ssm_layers {
+ let arrays = state.arrays(&[
+ ArrayId::SsmConvState(index),
+ ArrayId::SsmState(index),
+ ]);
+
+ let conv_state = arrays[0].borrow();
+ validate(
+ format!("updated_state.{}.conv_state", index).as_str(),
+ &conv_state,
+ Some(Transform::SsmConvState),
+ );
+ validate(
+ format!(
+ "activation_trace.layer_results.{}.updated_state.conv_state",
+ index
+ )
+ .as_str(),
+ &conv_state,
+ Some(Transform::SsmConvState),
+ );
+
+ let ssm_state = arrays[1].borrow();
+ validate(
+ format!("updated_state.{}.ssm_state", index).as_str(),
+ &ssm_state,
+ None,
+ );
+ validate(
+ format!(
+ "activation_trace.layer_results.{}.updated_state.ssm_state",
+ index
+ )
+ .as_str(),
+ &ssm_state,
+ None,
+ );
+ }
+
let expected_tokens =
Self::get_tokens_from_logits(&traces_view.leaf("logits").unwrap());
let produced_tokens =
@@ -488,23 +562,6 @@ impl Tracer {
};
}
- fn validate_array_with_name(
- data_type: DataType,
- traces_view: &ParameterTree<Rc<MTLContext>>,
- expected_array_path: String,
- produced_array: &Ref<MetalArray>,
- produced_transform: Option<Transform>,
- ) -> TracerValidationMetrics {
- let expected_array =
- traces_view.leaf(expected_array_path.as_str()).unwrap();
- return Self::validate_array(
- data_type,
- &expected_array,
- produced_array,
- produced_transform,
- );
- }
-
fn validate_array(
data_type: DataType,
expected_array: &MetalArray,
@@ -566,6 +623,29 @@ impl Tracer {
.to_owned();
(expected_view.to_owned(), reshaped)
},
+ Transform::SsmConvState => {
+ // expected: [1, T, D]
+ // produced: [D, K]
+ let produced_shape = produced_view.shape();
+ let history_len = produced_shape[1];
+ let dim = produced_shape[0];
+
+ // Permute expected to [1, D, T]
+ let permuted =
+ expected_view.permuted_axes(IxDyn(&[0, 2, 1]));
+ let total_time = permuted.shape()[2];
+ let start = total_time.saturating_sub(history_len);
+ // Slice last K elements from time axis: [1, D, K]
+ let sliced = permuted.slice(s![.., .., start..]);
+
+ let reshaped_expected = sliced
+ .into_owned()
+ .to_shape(IxDyn(&[dim, history_len]))
+ .expect("Failed to reshape SSM conv state slice")
+ .to_owned();
+
+ (reshaped_expected, produced_view.to_owned())
+ },
},
None => (expected_view.to_owned(), produced_view.to_owned()),
};
diff --git a/crates/uzu/tests/kv_cache_state_test.rs b/crates/uzu/tests/kv_cache_state_test.rs
index ae95ec293..3414d3569 100644
--- a/crates/uzu/tests/kv_cache_state_test.rs
+++ b/crates/uzu/tests/kv_cache_state_test.rs
@@ -6,9 +6,7 @@ use uzu::{
Array, DataType, DeviceContext,
backends::metal::{
KVCacheUpdate, KernelDataType, MTLContext,
- forward_pass::{
- KVCacheLayer, KVCacheLayerState, kv_cache::INVALID_POSITION,
- },
+ forward_pass::{INVALID_POSITION, KVCacheLayer, KVCacheLayerState},
},
};
diff --git a/crates/uzu/tests/quant_matmul_test.rs b/crates/uzu/tests/quant_matmul_test.rs
index 669bc489e..d9c8687ce 100644
--- a/crates/uzu/tests/quant_matmul_test.rs
+++ b/crates/uzu/tests/quant_matmul_test.rs
@@ -1,15 +1,16 @@
use std::time::Instant;
-use half::f16;
-use metal::{Device, MTLResourceOptions};
+use half::{bf16, f16};
+use metal::{Buffer, Device, MTLResourceOptions};
use uzu::{
DataType,
backends::metal::{
MTLContext,
kernel::quant_matmul::{
- QuantizedMatmulArguments, QuantizedMatmulKernel,
+ QuantizationType, QuantizedMatmulArguments, QuantizedMatmulKernel,
},
},
+ config::QuantizationMode,
};
fn create_test_context() -> Option<MTLContext> {
@@ -18,194 +19,533 @@ fn create_test_context() -> Option<MTLContext> {
MTLContext::new(device, command_queue).ok()
}
-// Packs 4-bit weights into bytes (4 values per 16-bit word, matching qdot expectations)
fn pack_u4_weights(values: &[u8]) -> Vec<u8> {
- let mut out = Vec::with_capacity((values.len() + 3) / 4 * 2); // 4 weights per 16-bit word
+ let mut out = Vec::with_capacity((values.len() + 3) / 4 * 2);
for chunk in values.chunks(4) {
- let w0 = (*chunk.get(0).unwrap_or(&0) as u16) & 0x0F; // Bits 0-3
- let w1 = ((*chunk.get(1).unwrap_or(&0) as u16) & 0x0F) << 4; // Bits 4-7
- let w2 = ((*chunk.get(2).unwrap_or(&0) as u16) & 0x0F) << 8; // Bits 8-11
- let w3 = ((*chunk.get(3).unwrap_or(&0) as u16) & 0x0F) << 12; // Bits 12-15
+ let w0 = (*chunk.get(0).unwrap_or(&0) as u16) & 0x0F;
+ let w1 = ((*chunk.get(1).unwrap_or(&0) as u16) & 0x0F) << 4;
+ let w2 = ((*chunk.get(2).unwrap_or(&0) as u16) & 0x0F) << 8;
+ let w3 = ((*chunk.get(3).unwrap_or(&0) as u16) & 0x0F) << 12;
let word: u16 = w0 | w1 | w2 | w3;
- out.push(word as u8); // Low byte
- out.push((word >> 8) as u8); // High byte
+ out.push(word as u8);
+ out.push((word >> 8) as u8);
}
out
}
+fn quantize_value(
+ value: f32,
+ dtype: DataType,
+) -> f32 {
+ match dtype {
+ DataType::F16 => f16::from_f32(value).to_f32(),
+ DataType::BF16 => bf16::from_f32(value).to_f32(),
+ _ => value,
+ }
+}
+
+fn quantize_slice(
+ values: &[f32],
+ dtype: DataType,
+) -> Vec<f32> {
+ values.iter().map(|&v| quantize_value(v, dtype)).collect()
+}
+
+struct ExecutionResult {
+ elapsed: f64,
+}
+
+fn create_test_weights(
+ output_dim: usize,
+ input_dim: usize,
+ weights_transposed: bool,
+ bits: usize,
+) -> Vec<u8> {
+ let mut weights_quant: Vec<u8> = Vec::with_capacity(output_dim * input_dim);
+
+ if weights_transposed {
+ // Weights stored as [output_dim × input_dim]
+ for row in 0..output_dim {
+ for _col in 0..input_dim {
+ let v = if bits == 4 {
+ (row as u8 + 1) & 0x0F
+ } else {
+ row as u8 + 1
+ };
+ weights_quant.push(v);
+ }
+ }
+ } else {
+ // Weights stored as [input_dim × output_dim]
+ for _row in 0..input_dim {
+ for col in 0..output_dim {
+ let v = if bits == 4 {
+ (col as u8 + 1) & 0x0F
+ } else {
+ col as u8 // Allow 0..255 range
+ };
+ weights_quant.push(v);
+ }
+ }
+ }
+
+ weights_quant
+}
+
+fn check_tolerance(
+ exp: f32,
+ got: f32,
+) -> bool {
+ let diff = (exp - got).abs() as f64;
+ // For F16 at boundaries (like 65504), machine epsilon is 32 (approx 0.05% relative error)
+ // We use a conservative relative tolerance of 0.2%
+ let rel_tol = 0.002;
+ let abs_tol = 0.1f64;
+ let tol = abs_tol.max(exp.abs() as f64 * rel_tol);
+ diff > tol
+}
+
+fn get_4bit_value(
+ data: &[u8],
+ index: usize,
+) -> f32 {
+ let word_idx = index / 4;
+ let word_offset = index % 4;
+ let byte_idx = word_idx * 2;
+
+ let word = if byte_idx + 1 < data.len() {
+ data[byte_idx] as u16 | ((data[byte_idx + 1] as u16) << 8)
+ } else {
+ 0
+ };
+
+ ((word >> (word_offset * 4)) & 0x0F) as f32
+}
+
+fn get_zp_value(
+ zero_points: &[u8],
+ stride: usize,
+ row_idx: usize,
+ group_idx: usize,
+ bits: usize,
+) -> f32 {
+ if bits == 4 {
+ let byte_index = row_idx * stride + (group_idx >> 1);
+ let byte = zero_points.get(byte_index).copied().unwrap_or(0);
+ if (group_idx & 1) == 0 {
+ (byte & 0x0F) as f32
+ } else {
+ ((byte >> 4) & 0x0F) as f32
+ }
+ } else {
+ zero_points.get(row_idx * stride + group_idx).copied().unwrap_or(0)
+ as f32
+ }
+}
+
fn cpu_reference(
- m: usize,
- n: usize,
- k: usize,
- a: &[f32], // A matrix (M x K)
- b_quant: &[u8], // B matrix (N x K), quantized and packed, (N * K / 2) in size
- scales: &[f32], // scales for B (N x ceil(K/group_size))
- biases: &[f32], // biases for B (N x ceil(K/group_size))
- transpose_b: bool, // Whether B matrix weights are stored in transposed layout
+ batch: usize,
+ output_dim: usize,
+ input_dim: usize,
+ a: &[f32],
+ b_quant: &[u8],
+ scales: &[f32],
+ biases: &[f32],
+ weights_transposed: bool,
+ group_size: usize,
+ dtype: DataType,
+ bits: usize,
+ quantization_type: QuantizationType,
+ zero_points: &[u8],
+ zero_points_stride: usize,
) -> Vec<f32> {
- let group_size = 64;
- let num_groups = (k + group_size - 1) / group_size;
- let mut y = vec![0.0f32; m * n];
- for i in 0..m {
- for j in 0..n {
- let mut acc = 0.0f64;
- for g in 0..num_groups {
- let scale = scales[j * num_groups + g] as f64;
- let bias = biases[j * num_groups + g] as f64;
- let l_start = g * group_size;
- let l_end = (l_start + group_size).min(k);
- let mut group_acc = 0.0f64;
- let mut group_sum = 0.0f64;
- for l in l_start..l_end {
- // Weight indexing based on kernel expectations:
- // Non-transposed kernel expects: W[N][K] layout -> w[output_idx * k + input_idx]
- // Transposed kernel expects: W[K][N] layout -> w[input_idx * n + output_idx]
- let weight_linear_idx = if transpose_b {
- l * n + j // W[K][N]: w[k_idx * n + n_idx]
+ let num_groups_k = (input_dim + group_size - 1) / group_size;
+ let num_groups_n = (output_dim + group_size - 1) / group_size;
+ let num_groups = if !weights_transposed {
+ num_groups_n
+ } else {
+ num_groups_k
+ };
+
+ let mut y = vec![0.0f32; batch * output_dim];
+ for i in 0..batch {
+ for j in 0..output_dim {
+ let mut acc = 0.0f32;
+ if !weights_transposed {
+ let group_idx = j / group_size;
+ for l in 0..input_dim {
+ let weight_linear_idx = if weights_transposed {
+ j * input_dim + l
} else {
- j * k + l // W[N][K]: w[n_idx * k + k_idx]
+ l * output_dim + j
};
- let word_idx = weight_linear_idx / 4; // 4 weights per 16-bit word
- let word_offset = weight_linear_idx % 4; // Which nibble in the word
- let byte_idx = word_idx * 2; // 2 bytes per word
-
- let word = if byte_idx + 1 < b_quant.len() {
- b_quant[byte_idx] as u16
- | ((b_quant[byte_idx + 1] as u16) << 8)
+ let val_q = if bits == 4 {
+ get_4bit_value(b_quant, weight_linear_idx)
} else {
- 0
+ b_quant[weight_linear_idx] as f32
};
- let val_q = match word_offset {
- 0 => word & 0x000F, // Bits 0-3
- 1 => (word & 0x00F0) >> 4, // Bits 4-7
- 2 => (word & 0x0F00) >> 8, // Bits 8-11
- 3 => (word & 0xF000) >> 12, // Bits 12-15
- _ => 0,
- } as f64;
- let val_a = a[i * k + l] as f64;
- group_acc += val_a * val_q;
- group_sum += val_a;
+ let val_a = a[i * input_dim + l];
+ let scale = scales[l * num_groups + group_idx];
+ let bias =
+ if quantization_type == QuantizationType::ZeroPoint {
+ let zp_val_qvm = get_zp_value(
+ zero_points,
+ zero_points_stride,
+ l,
+ group_idx,
+ bits,
+ );
+ -scale * zp_val_qvm
+ } else {
+ biases[l * num_groups + group_idx]
+ };
+ acc += val_a * (scale * val_q + bias);
+ }
+ } else {
+ for g in 0..num_groups {
+ let scale = scales[j * num_groups + g];
+ let bias = match quantization_type {
+ QuantizationType::ZeroPoint => {
+ let zp = get_zp_value(
+ zero_points,
+ zero_points_stride,
+ j,
+ g,
+ bits,
+ );
+ -scale * zp
+ },
+ QuantizationType::Mlx => biases[j * num_groups + g],
+ };
+ let l_start = g * group_size;
+ let l_end = (l_start + group_size).min(input_dim);
+ let mut group_acc = 0.0f32;
+ let mut group_sum = 0.0f32;
+ for l in l_start..l_end {
+ let weight_linear_idx = if weights_transposed {
+ j * input_dim + l
+ } else {
+ l * output_dim + j
+ };
+
+ let val_q = if bits == 4 {
+ get_4bit_value(b_quant, weight_linear_idx)
+ } else {
+ b_quant[weight_linear_idx] as f32
+ };
+
+ let val_a = a[i * input_dim + l];
+ group_acc += val_a * val_q;
+ group_sum += val_a;
+ }
+ acc += scale * group_acc + bias * group_sum;
}
- acc += scale * group_acc + bias * group_sum;
}
- y[i * n + j] = acc as f32;
+ y[i * output_dim + j] = quantize_value(acc, dtype);
}
}
y
}
+struct TestQuantParams {
+ scales: Vec<f32>,
+ scales_quant: Vec<f32>,
+ biases: Vec<f32>,
+ zero_points: Vec<u8>,
+ zero_points_stride: usize,
+}
+
+fn generate_test_quant_params(
+ output_dim: usize,
+ input_dim: usize,
+ group_size: usize,
+ data_type: DataType,
+ bits: usize,
+ quantization_type: QuantizationType,
+ weights_transposed: bool,
+ randomize_zp: bool,
+) -> TestQuantParams {
+ let num_groups_k = (input_dim + group_size - 1) / group_size;
+ let num_groups_n = (output_dim + group_size - 1) / group_size;
+ let num_groups = if !weights_transposed {
+ num_groups_n
+ } else {
+ num_groups_k
+ };
+ let primary_dim = if !weights_transposed {
+ input_dim
+ } else {
+ output_dim
+ };
+
+ let len = primary_dim * num_groups;
+ let scales = vec![1.0; len];
+ let scales_quant = quantize_slice(&scales, data_type);
+ let mut biases = vec![0.0; len];
+
+ let zero_points_stride = if bits == 4 {
+ ((num_groups + 1) / 2).max(1)
+ } else {
+ num_groups
+ };
+ let zero_points_len = if !weights_transposed {
+ input_dim * zero_points_stride
+ } else {
+ output_dim * zero_points_stride
+ };
+ let mut zero_points = vec![0u8; zero_points_len];
+
+ if quantization_type == QuantizationType::ZeroPoint && randomize_zp {
+ if !weights_transposed {
+ // GMM/QVM non-transposed: Use [K][N_groups] layout for generation
+ for k in 0..input_dim {
+ for g in 0..num_groups {
+ let k_eff = k / group_size;
+ let base_val = ((k_eff * 5 + g * 7) & 0xFF) as u8;
+ let zp_val_u8 = if bits == 4 {
+ base_val & 0x0F
+ } else {
+ base_val
+ };
+ if bits == 4 {
+ let byte_index = k * zero_points_stride + (g >> 1);
+ if (g & 1) == 0 {
+ zero_points[byte_index] = (zero_points[byte_index]
+ & 0xF0)
+ | (zp_val_u8 & 0x0F);
+ } else {
+ zero_points[byte_index] = (zero_points[byte_index]
+ & 0x0F)
+ | ((zp_val_u8 & 0x0F) << 4);
+ }
+ } else {
+ zero_points[k * zero_points_stride + g] = zp_val_u8;
+ }
+
+ // Note: scales are [input_dim][num_groups] in this case?
+ // No, scales are 1.0.
+ // Biases logic needs to use same indexing!
+ // But biases is flat buffer.
+ // Index: k * num_groups + g.
+ let s = scales_quant[k * num_groups + g];
+ let zp_val = if bits == 4 {
+ (zp_val_u8 & 0x0F) as f32
+ } else {
+ zp_val_u8 as f32
+ };
+ biases[k * num_groups + g] =
+ quantize_value(-s * zp_val, data_type);
+ }
+ }
+ } else {
+ for j in 0..output_dim {
+ for g in 0..num_groups {
+ let base_val = if weights_transposed {
+ j + 3 * g
+ } else {
+ 3 * g
+ };
+ let zp_val: u8 = if bits == 4 {
+ (base_val as u8) & 0x0F
+ } else {
+ base_val as u8
+ };
+
+ if bits == 4 {
+ let byte_index = j * zero_points_stride + (g >> 1);
+ if (g & 1) == 0 {
+ zero_points[byte_index] = (zero_points[byte_index]
+ & 0xF0)
+ | (zp_val & 0x0F);
+ } else {
+ zero_points[byte_index] = (zero_points[byte_index]
+ & 0x0F)
+ | ((zp_val & 0x0F) << 4);
+ }
+ } else {
+ let byte_index = j * zero_points_stride + g;
+ zero_points[byte_index] = zp_val;
+ }
+
+ let s = scales_quant[j * num_groups + g];
+ let b = quantize_value(-s * (zp_val as f32), data_type);
+ biases[j * num_groups + g] = b;
+ }
+ }
+ }
+ }
+
+ if quantization_type == QuantizationType::Mlx {
+ if !weights_transposed {
+ for k in 0..input_dim {
+ for g in 0..num_groups {
+ let base_val = g * 3;
+ let bias_val = (base_val % 19) as f32 * 0.125;
+ biases[k * num_groups + g] =
+ quantize_value(bias_val, data_type);
+ }
+ }
+ } else {
+ for j in 0..output_dim {
+ for g in 0..num_groups {
+ let base_val = if weights_transposed {
+ j * 7 + g * 3
+ } else {
+ g * 3
+ };
+ let bias_val = (base_val % 19) as f32 * 0.125;
+ biases[j * num_groups + g] =
+ quantize_value(bias_val, data_type);
+ }
+ }
+ }
+ }
+
+ TestQuantParams {
+ scales,
+ scales_quant,
+ biases,
+ zero_points,
+ zero_points_stride,
+ }
+}
+
+fn buffer_from_f32_slice(
+ ctx: &MTLContext,
+ dtype: DataType,
+ values: &[f32],
+) -> Buffer {
+ match dtype {
+ DataType::F16 => {
+ let data: Vec<f16> =
+ values.iter().map(|&v| f16::from_f32(v)).collect();
+ ctx.device.new_buffer_with_data(
+ data.as_ptr() as *const std::ffi::c_void,
+ (data.len() * std::mem::size_of::<f16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ )
+ },
+ DataType::BF16 => {
+ let data: Vec<bf16> =
+ values.iter().map(|&v| bf16::from_f32(v)).collect();
+ ctx.device.new_buffer_with_data(
+ data.as_ptr() as *const std::ffi::c_void,
+ (data.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ )
+ },
+ DataType::F32 => ctx.device.new_buffer_with_data(
+ values.as_ptr() as *const std::ffi::c_void,
+ (values.len() * std::mem::size_of::<f32>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ ),
+ other => {
+ panic!("Unsupported dtype for buffer_from_f32_slice: {:?}", other)
+ },
+ }
+}
+
fn execute_quantized_matmul(
ctx: &MTLContext,
- m: usize,
- n: usize,
- k: usize,
- kernel_name: &str,
- cpu_transpose: bool,
+ batch: usize,
+ input_dim: usize,
+ output_dim: usize,
+ weights_transposed: bool,
iterations: usize,
validate: bool,
+ quantization_type: QuantizationType,
randomize_zp: bool,
-) -> f64 {
- // Prepare deterministic weights: w(row,k) = row+1
- // Always create weights in the same layout (test_m × test_k)
- let mut weights_q4: Vec<u8> = Vec::with_capacity(m * k);
- for row in 0..m {
- for _k in 0..k {
- let v = (row as u8 + 1) & 0x0F;
- weights_q4.push(v);
- }
- }
- let weights_packed = pack_u4_weights(&weights_q4);
-
- let num_groups = (k + 63) / 64;
- let scales: Vec<f16> = vec![f16::from_f32(1.0); m * num_groups];
- let mut biases: Vec<f16> = vec![f16::from_f32(0.0); m * num_groups];
-
- // Prepare input data
- let (x_f32, x_f16) = if n == 1 {
- // GEMV case: single input vector
- let x_f32: Vec<f32> = (1..=k).map(|i| i as f32 / k as f32).collect();
- let x_f16: Vec<f16> = x_f32.iter().map(|&v| f16::from_f32(v)).collect();
- (x_f32, x_f16)
+ group_size: usize,
+ data_type: DataType,
+ bits: usize,
+) -> ExecutionResult {
+ let weights_quant =
+ create_test_weights(output_dim, input_dim, weights_transposed, bits);
+ let weights_packed = if bits == 4 {
+ pack_u4_weights(&weights_quant)
} else {
- // GEMM case: multiple input vectors (column-major)
- let mut x_f32: Vec<f32> = Vec::with_capacity(k * n);
- for _col in 0..n {
- for i in 0..k {
- x_f32.push((i + 1) as f32 / k as f32);
+ weights_quant.clone()
+ };
+
+ let params = generate_test_quant_params(
+ output_dim,
+ input_dim,
+ group_size,
+ data_type,
+ bits,
+ quantization_type,
+ weights_transposed,
+ randomize_zp,
+ );
+ // X is batch × input_dim
+ let x_f32: Vec<f32> = if batch == 1 {
+ // Vector case: 1 × input_dim
+ (1..=input_dim).map(|i| i as f32 / input_dim as f32).collect()
+ } else {
+ let mut x_vals: Vec<f32> = Vec::with_capacity(batch * input_dim);
+ for _row in 0..batch {
+ for i in 0..input_dim {
+ x_vals.push((i + 1) as f32 / input_dim as f32);
}
}
- let x_f16: Vec<f16> = x_f32.iter().map(|&v| f16::from_f32(v)).collect();
- (x_f32, x_f16)
+ x_vals
};
+ let x_quant = quantize_slice(&x_f32, data_type);
- // Create buffers
let w_buf = ctx.device.new_buffer_with_data(
weights_packed.as_ptr() as *const _,
(weights_packed.len() * std::mem::size_of::<u8>()) as u64,
MTLResourceOptions::StorageModeShared,
);
- let s_buf = ctx.device.new_buffer_with_data(
- scales.as_ptr() as *const _,
- (scales.len() * std::mem::size_of::<f16>()) as u64,
- MTLResourceOptions::StorageModeShared,
- );
- // Build zero-points buffer
- let mut zps_bytes = vec![0u8; m * ((num_groups + 1) / 2)];
- if randomize_zp {
- // Randomized U8 zero-points per group and corresponding float biases.
- // even g -> low nibble, odd g -> high nibble
- for j in 0..m {
- for g in 0..num_groups {
- let zp_val: u8 = ((j + 3 * g) as u8) & 0x0F; // deterministic 0..15
- let byte_index = j * ((num_groups + 1) / 2) + (g >> 1);
- if (g & 1) == 0 {
- zps_bytes[byte_index] =
- (zps_bytes[byte_index] & 0xF0) | (zp_val & 0x0F);
- } else {
- zps_bytes[byte_index] =
- (zps_bytes[byte_index] & 0x0F) | ((zp_val & 0x0F) << 4);
- }
- // bias = -scale * zp
- let s = scales[j * num_groups + g].to_f32();
- let b = -s * (zp_val as f32);
- biases[j * num_groups + g] = f16::from_f32(b);
- }
- }
- }
- let b_buf = ctx.device.new_buffer_with_data(
- zps_bytes.as_ptr() as *const _,
- (zps_bytes.len() * std::mem::size_of::<u8>()) as u64,
- MTLResourceOptions::StorageModeShared,
- );
- let x_buf = ctx.device.new_buffer_with_data(
- x_f16.as_ptr() as *const _,
- (x_f16.len() * std::mem::size_of::<f16>()) as u64,
- MTLResourceOptions::StorageModeShared,
- );
+ let s_buf = buffer_from_f32_slice(ctx, data_type, &params.scales);
+
+ let b_buf = match quantization_type {
+ QuantizationType::ZeroPoint => ctx.device.new_buffer_with_data(
+ params.zero_points.as_ptr() as *const _,
+ (params.zero_points.len() * std::mem::size_of::<u8>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ ),
+ QuantizationType::Mlx => {
+ buffer_from_f32_slice(ctx, data_type, &params.biases)
+ },
+ };
+ let x_buf = buffer_from_f32_slice(ctx, data_type, &x_f32);
let y_buf = ctx.device.new_buffer(
- (m * n * std::mem::size_of::<f16>()) as u64,
+ (batch * output_dim * data_type.size_in_bytes()) as u64,
MTLResourceOptions::StorageModeShared,
);
- // Create kernel
- let kernel =
- QuantizedMatmulKernel::new(&ctx, DataType::F16, kernel_name).unwrap();
+ let kernel = QuantizedMatmulKernel::new(
+ &ctx,
+ data_type,
+ group_size,
+ input_dim,
+ output_dim,
+ match bits {
+ 4 => QuantizationMode::UInt4,
+ 8 => QuantizationMode::Int8,
+ _ => panic!("Unsupported bits: {}", bits),
+ },
+ quantization_type,
+ weights_transposed,
+ )
+ .unwrap();
- // Warmup (only for benchmarks)
if iterations > 1 {
for _ in 0..3 {
let args = QuantizedMatmulArguments {
a_buffer: &x_buf,
b_buffer: &w_buf,
scales_buffer: &s_buf,
- zero_points_buffer: &b_buf,
+ zero_points_or_biases_buffer: &b_buf,
output_buffer: &y_buf,
- m: n as i32,
- n: m as i32,
- k: k as i32,
+ batch: batch as i32,
+ input_dim: input_dim as i32,
+ output_dim: output_dim as i32,
+ quantization_type,
};
let cb_ref = ctx.command_queue.new_command_buffer();
let encoder = cb_ref.new_compute_command_encoder();
@@ -216,18 +556,18 @@ fn execute_quantized_matmul(
}
}
- // Execute and time
let start = Instant::now();
for _ in 0..iterations {
let args = QuantizedMatmulArguments {
a_buffer: &x_buf,
b_buffer: &w_buf,
scales_buffer: &s_buf,
- zero_points_buffer: &b_buf,
+ zero_points_or_biases_buffer: &b_buf,
output_buffer: &y_buf,
- m: n as i32,
- n: m as i32,
- k: k as i32,
+ batch: batch as i32,
+ input_dim: input_dim as i32,
+ output_dim: output_dim as i32,
+ quantization_type,
};
let cb_ref = ctx.command_queue.new_command_buffer();
let encoder = cb_ref.new_compute_command_encoder();
@@ -238,134 +578,194 @@ fn execute_quantized_matmul(
}
let elapsed = start.elapsed();
- // Validate if requested
if validate {
- let gpu_m = n; // GPU sees test_n as M
- let gpu_n = m; // GPU sees test_m as N
- let gpu_k = k; // GPU sees test_k as K
-
let y_expected = cpu_reference(
- gpu_m,
- gpu_n,
- gpu_k,
- &x_f32,
+ batch,
+ output_dim,
+ input_dim,
+ &x_quant,
&weights_packed,
- &scales.iter().map(|&v| v.to_f32()).collect::<Vec<_>>(),
- &biases.iter().map(|&v| v.to_f32()).collect::<Vec<_>>(),
- cpu_transpose,
+ &params.scales_quant,
+ &params.biases,
+ weights_transposed,
+ group_size,
+ data_type,
+ bits,
+ quantization_type,
+ &params.zero_points,
+ params.zero_points_stride,
);
- let y_ptr = y_buf.contents() as *const f16;
- let y_out = unsafe { std::slice::from_raw_parts(y_ptr, m * n) };
- let y_out_f32: Vec<f32> = y_out.iter().map(|&v| v.to_f32()).collect();
-
- let tol = if randomize_zp {
- 2.5
- } else {
- 1.0
- };
- let display_size = if n == 1 {
- m
- } else {
- n
+ let y_out_f32: Vec<f32> = match data_type {
+ DataType::F16 => {
+ let y_ptr = y_buf.contents() as *const f16;
+ let y_out = unsafe {
+ std::slice::from_raw_parts(y_ptr, batch * output_dim)
+ };
+ y_out.iter().map(|&v| v.to_f32()).collect()
+ },
+ DataType::BF16 => {
+ let y_ptr = y_buf.contents() as *const bf16;
+ let y_out = unsafe {
+ std::slice::from_raw_parts(y_ptr, batch * output_dim)
+ };
+ y_out.iter().map(|&v| v.to_f32()).collect()
+ },
+ DataType::F32 => {
+ let y_ptr = y_buf.contents() as *const f32;
+ let y_out = unsafe {
+ std::slice::from_raw_parts(y_ptr, batch * output_dim)
+ };
+ y_out.to_vec()
+ },
+ other => panic!("Unsupported dtype for validation: {:?}", other),
};
- println!(
- "first {} expected: {:?}",
- display_size,
- &y_expected[..display_size]
- );
- println!(
- "first {} got: {:?}",
- display_size,
- &y_out_f32[..display_size]
- );
+
+ let mut debug_prints = 0;
for (i, (&exp, &got)) in
y_expected.iter().zip(y_out_f32.iter()).enumerate()
{
let diff = (exp - got).abs();
- assert!(
- diff <= tol,
- "M={} N={} K={} idx {} diff {} exp {} got {}",
- m,
- n,
- k,
- i,
- diff,
- exp,
- got
+
+ if check_tolerance(exp, got) {
+ if debug_prints < 16 {
+ println!(
+ "\n detail idx {} diff {} exp {} got {}",
+ i, diff, exp, got
+ );
+ }
+ debug_prints += 1;
+ }
+ }
+
+ if debug_prints > 0 {
+ let first_error = y_expected
+ .iter()
+ .zip(y_out_f32.iter())
+ .enumerate()
+ .find(|&(_, (&e, &g))| check_tolerance(e, g))
+ .map(|(i, _)| i)
+ .unwrap_or(0);
+ let last_error = y_expected
+ .iter()
+ .zip(y_out_f32.iter())
+ .enumerate()
+ .filter(|&(_, (&e, &g))| check_tolerance(e, g))
+ .last()
+ .map(|(i, _)| i)
+ .unwrap_or(0);
+ println!(
+ "\nTotal errors: {} out of {} outputs",
+ debug_prints,
+ batch * output_dim
);
+ println!("Error range: indices {}-{}", first_error, last_error);
+ println!(
+ "Dims batch={} output_dim={} input_dim={}",
+ batch, output_dim, input_dim
+ );
+ panic!("Validation failed with {} mismatches", debug_prints);
}
- }
- elapsed.as_secs_f64()
+ ExecutionResult {
+ elapsed: elapsed.as_secs_f64(),
+ }
+ } else {
+ ExecutionResult {
+ elapsed: elapsed.as_secs_f64(),
+ }
+ }
}
-fn run_gemv_test(
- ctx: &MTLContext,
- m: usize,
- k: usize,
-) {
- println!("--- Testing GEMV M={}, K={} ---", m, k);
- // GEMV: weights are in W[N][K] layout, CPU uses them as-is
- execute_quantized_matmul(
- ctx,
- m,
- 1,
- k,
- "qmv_f16_g64_b4",
- false,
- 1,
- true,
- true,
- );
- println!("✅ GEMV M={}, K={} passed", m, k);
+struct TestConfig {
+ quant_type: QuantizationType,
+ bits: usize,
+ data_type: DataType,
+ group_size: usize,
}
-fn run_qvm_test(
+const QMV_DIMS: &[(usize, usize)] = &[(128, 512), (512, 1024), (1024, 4096)];
+const QVM_DIMS: &[(usize, usize)] = &[(128, 512), (512, 1024), (1024, 4096)];
+const QMM_DIMS: &[(usize, usize, usize)] =
+ &[(64, 64, 64), (512, 512, 1024), (128, 128, 256)];
+
+fn run_kernel_test(
ctx: &MTLContext,
- n: usize,
- k: usize,
-) {
- println!("--- Testing QVM N={}, K={} ---", n, k);
- // QVM: weights are in W[N][K] layout, CPU uses them as-is
+ batch: usize,
+ output_dim: usize,
+ input_dim: usize,
+ weights_transposed: bool,
+ config: &TestConfig,
+ validate: bool,
+ iterations: usize,
+) -> ExecutionResult {
+ let randomize_zp = config.quant_type == QuantizationType::ZeroPoint;
+
execute_quantized_matmul(
ctx,
- 1,
- n,
- k,
- "qvm_f16_g64_b4",
- false,
- 1,
- true,
- true,
- );
- println!("✅ QVM N={}, K={} passed", n, k);
+ batch,
+ input_dim,
+ output_dim,
+ weights_transposed,
+ iterations,
+ validate,
+ config.quant_type,
+ randomize_zp,
+ config.group_size,
+ config.data_type,
+ config.bits,
+ )
}
#[test]
-fn test_quant_gemv() {
+fn test_quant_gmv() {
let ctx = match create_test_context() {
Some(c) => c,
None => {
- println!("Metal not available — skipping GEMV test");
+ println!("Metal not available — skipping QMV test");
return;
},
};
- run_gemv_test(&ctx, 3, 64);
- run_gemv_test(&ctx, 1, 128);
- run_gemv_test(&ctx, 7, 256);
- run_gemv_test(&ctx, 13, 512);
- run_gemv_test(&ctx, 13, 511);
- run_gemv_test(&ctx, 8, 64);
- run_gemv_test(&ctx, 9, 64);
- run_gemv_test(&ctx, 25, 128);
- run_gemv_test(&ctx, 31, 512);
+ let configs = vec![
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ ];
+
+ for config in &configs {
+ for &(output_dim, input_dim) in QMV_DIMS {
+ run_kernel_test(
+ &ctx, 1, output_dim, input_dim, true, config, true, 1,
+ );
+ }
+ }
}
#[test]
-fn test_quant_qevm() {
+fn test_quant_qvm() {
let ctx = match create_test_context() {
Some(c) => c,
None => {
@@ -374,222 +774,207 @@ fn test_quant_qevm() {
},
};
- run_qvm_test(&ctx, 3, 64);
- run_qvm_test(&ctx, 1, 128);
- run_qvm_test(&ctx, 7, 256);
- run_qvm_test(&ctx, 13, 512);
- run_qvm_test(&ctx, 13, 511);
- run_qvm_test(&ctx, 8, 64);
- run_qvm_test(&ctx, 9, 64);
- run_qvm_test(&ctx, 25, 128);
- run_qvm_test(&ctx, 31, 512);
-}
-
-fn run_gemm_test(
- ctx: &MTLContext,
- m: usize,
- n: usize,
- k: usize,
-) {
- println!("--- Testing GEMM M={}, N={}, K={} ---", m, n, k);
- // GEMM: weights are in W[N][K] layout, CPU needs to transpose for correct computation
- execute_quantized_matmul(
- ctx,
- m,
- n,
- k,
- "qmm_f16_g64_b4",
- true,
- 1,
- true,
- false,
- );
- println!("✅ GEMM M={}, N={}, K={} passed", m, n, k);
-}
+ let configs = vec![
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ ];
-fn run_gemm_transposed_test(
- ctx: &MTLContext,
- m: usize,
- n: usize,
- k: usize,
-) {
- println!("--- Testing GEMM Transposed M={}, N={}, K={} ---", m, n, k);
- // GEMM Transposed: weights are in W[N][K] but kernel expects W[K][N], CPU uses them as-is
- execute_quantized_matmul(
- ctx,
- m,
- n,
- k,
- "qmm_transposed_f16_g64_b4",
- false,
- 1,
- true,
- true,
- );
- println!("✅ GEMM Transposed M={}, N={}, K={} passed", m, n, k);
+ for config in &configs {
+ for &(output_dim, input_dim) in QVM_DIMS {
+ run_kernel_test(
+ &ctx, 1, output_dim, input_dim, false, config, true, 1,
+ );
+ }
+ }
}
#[test]
-fn test_quant_gemm() {
+fn test_quant_gmm() {
let ctx = match create_test_context() {
Some(c) => c,
None => {
- println!("Metal not available — skipping GEMM test");
+ println!("Metal not available — skipping QMM test");
return;
},
};
- run_gemm_test(&ctx, 1, 1, 128);
- run_gemm_test(&ctx, 8, 16, 256);
- run_gemm_test(&ctx, 16, 8, 511);
- run_gemm_test(&ctx, 9, 9, 64);
- run_gemm_test(&ctx, 25, 17, 128);
+ let configs = vec![
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ ];
+
+ for config in &configs {
+ for &(batch, output_dim, input_dim) in QMM_DIMS {
+ run_kernel_test(
+ &ctx, batch, output_dim, input_dim, false, config, true, 1,
+ );
+ }
+ }
}
#[test]
-fn test_quant_gemm_transposed() {
+fn test_quant_gmm_transposed() {
let ctx = match create_test_context() {
Some(c) => c,
None => {
- println!("Metal not available — skipping GEMM transposed test");
+ println!("Metal not available — skipping QMM transposed test");
return;
},
};
- run_gemm_transposed_test(&ctx, 1, 1, 128);
- run_gemm_transposed_test(&ctx, 8, 16, 256);
- run_gemm_transposed_test(&ctx, 16, 8, 511);
- run_gemm_transposed_test(&ctx, 9, 9, 64);
- run_gemm_transposed_test(&ctx, 25, 17, 128);
-}
-
-fn benchmark_quantized_gemv(
- ctx: &MTLContext,
- m: usize,
- k: usize,
- iterations: usize,
-) -> f64 {
- execute_quantized_matmul(
- ctx,
- m,
- 1,
- k,
- "qmv_f16_g64_b4",
- false,
- iterations,
- false,
- true,
- )
-}
-
-fn benchmark_quantized_qevm(
- ctx: &MTLContext,
- n: usize,
- k: usize,
- iterations: usize,
-) -> f64 {
- execute_quantized_matmul(
- ctx,
- 1,
- n,
- k,
- "qvm_f16_g64_b4",
- false,
- iterations,
- false,
- true,
- )
-}
+ let configs = vec![
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 4,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 8,
+ data_type: DataType::F32,
+ group_size: 64,
+ },
+ ];
-fn benchmark_quantized_gemm(
- ctx: &MTLContext,
- m: usize,
- n: usize,
- k: usize,
- iterations: usize,
-) -> f64 {
- execute_quantized_matmul(
- ctx,
- m,
- n,
- k,
- "qmm_f16_g64_b4",
- true,
- iterations,
- false,
- true,
- )
+ for config in &configs {
+ for &(batch, output_dim, input_dim) in QMM_DIMS {
+ run_kernel_test(
+ &ctx, batch, output_dim, input_dim, true, config, true, 1,
+ );
+ }
+ }
}
-#[ignore]
#[test]
-fn test_quantized_matmul_performance() {
+#[ignore]
+fn test_quant_matmul_perf() {
let ctx = match create_test_context() {
Some(c) => c,
None => {
- println!("Metal not available — skipping performance test");
+ println!("Metal not available — skipping Perf test");
return;
},
};
- println!("\n🚀 QUANTIZED MATMUL PERFORMANCE BENCHMARKS");
- println!("==========================================");
-
- // Test different sizes
- let test_configs = vec![
- // (M, N, K, iterations, description)
- (512, 1, 512, 100, "Small GEMV (512×512 × 512×1)"),
- (1024, 1, 1024, 50, "Medium GEMV (1024×1024 × 1024×1)"),
- (2048, 1, 2048, 20, "Large GEMV (2048×2048 × 2048×1)"),
- (4096, 1, 4096, 10, "XLarge GEMV (4096×4096 × 4096×1)"),
- (1, 512, 512, 100, "Small QVM (1×512 × 512×512)"),
- (1, 1024, 1024, 50, "Medium QVM (1×1024 × 1024×1024)"),
- (1, 2048, 2048, 20, "Large QVM (1×2048 × 2048×2048)"),
- (1, 4096, 4096, 10, "XLarge QVM (1×4096 × 4096×4096)"),
- (512, 16, 512, 50, "Small GEMM (512×512 × 512×16)"),
- (1024, 32, 1024, 20, "Medium GEMM (1024×1024 × 1024×32)"),
- (2048, 64, 2048, 10, "Large GEMM (2048×2048 × 2048×64)"),
- (4096, 128, 4096, 5, "XLarge GEMM (4096×4096 × 4096×128)"),
+ // Llama 3 8B approximate shapes
+ let shapes = vec![
+ // Decoding (M=1)
+ (1, 4096, 4096),
+ (1, 14336, 4096),
+ (1, 4096, 14336),
+ // Prefill (Small batch M=128)
+ (128, 4096, 4096),
];
- for (m, n, k, iterations, description) in test_configs {
- let ops = 2.0 * (m as f64) * (n as f64) * (k as f64);
-
- if n == 1 {
- // GEMV
- let time = benchmark_quantized_gemv(&ctx, m, k, iterations);
- let avg_time = time / (iterations as f64);
- let throughput = (ops / avg_time) / 1e12;
+ let configs = vec![
+ // 4-bit Mlx BF16
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 4,
+ data_type: DataType::BF16,
+ group_size: 128,
+ },
+ // 8-bit Mlx BF16
+ TestConfig {
+ quant_type: QuantizationType::Mlx,
+ bits: 8,
+ data_type: DataType::BF16,
+ group_size: 128,
+ },
+ // 4-bit ZP F16
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 4,
+ data_type: DataType::F16,
+ group_size: 64,
+ },
+ // 8-bit ZP F16
+ TestConfig {
+ quant_type: QuantizationType::ZeroPoint,
+ bits: 8,
+ data_type: DataType::F16,
+ group_size: 64,
+ },
+ ];
- println!("{}", description);
- println!(
- " Time: {:.4}ms/iter, Throughput: {:.4} TFLOPS",
- avg_time * 1000.0,
- throughput
- );
- } else if m == 1 {
- // QVM
- let time = benchmark_quantized_qevm(&ctx, n, k, iterations);
- let avg_time = time / (iterations as f64);
- let throughput = (ops / avg_time) / 1e12;
+ println!(
+ "{:<20} | {:<10} | {:<6} | {:<5} | {:<5} | {:<15}",
+ "Kernel Config", "M x N x K", "Type", "Bits", "Group", "Avg Duration"
+ );
+ println!("{}", "-".repeat(85));
- println!("{}", description);
- println!(
- " Time: {:.4}ms/iter, Throughput: {:.4} TFLOPS",
- avg_time * 1000.0,
- throughput
+ for config in &configs {
+ for &(batch, output_dim, input_dim) in &shapes {
+ let result = run_kernel_test(
+ &ctx, batch, output_dim, input_dim, false, config, false, 20,
);
- } else {
- // GEMM
- let time = benchmark_quantized_gemm(&ctx, m, n, k, iterations);
- let avg_time = time / (iterations as f64);
- let throughput = (ops / avg_time) / 1e12;
+ let avg = result.elapsed / 20.0 * 1000.0; // ms
- println!("{}", description);
println!(
- " Time: {:.4}ms/iter, Throughput: {:.4} TFLOPS",
- avg_time * 1000.0,
- throughput
+ "{:<20} | {:<10} | {:<6} | {:<5} | {:<5} | {:.4} ms",
+ format!("{:?}", config.quant_type),
+ format!("{}x{}x{}", batch, output_dim, input_dim),
+ format!("{:?}", config.data_type),
+ config.bits,
+ config.group_size,
+ avg
);
}
}
diff --git a/crates/uzu/tests/ssd_prefill_kernel_test.rs b/crates/uzu/tests/ssd_prefill_kernel_test.rs
new file mode 100644
index 000000000..b357df5f2
--- /dev/null
+++ b/crates/uzu/tests/ssd_prefill_kernel_test.rs
@@ -0,0 +1,581 @@
+#![cfg(target_os = "macos")]
+
+use std::mem::size_of;
+
+use metal::MTLResourceOptions;
+use uzu::{
+ backends::metal::{
+ KernelDataType, MTLContext,
+ kernel::ssm::{
+ SSDPrefillArguments, SSDPrefillKernel, SSDPrefillMode,
+ conv1d_scan::{Conv1dScanArguments, Conv1dScanKernel},
+ },
+ },
+ config::Activation,
+};
+
+const STORAGE_MODE: MTLResourceOptions = MTLResourceOptions::StorageModeShared;
+
+fn silu_scalar(x: f32) -> f32 {
+ let y = 1.0 / (1.0 + (-x).exp());
+ x * y
+}
+
+fn softplus_f32(x: f32) -> f32 {
+ if x > 20.0 {
+ x
+ } else {
+ (1.0 + x.exp()).ln()
+ }
+}
+
+fn create_context() -> Option<MTLContext> {
+ let device = metal::Device::system_default()?;
+ let command_queue = device.new_command_queue();
+ MTLContext::new(device, command_queue).ok()
+}
+
+fn write_buffer(
+ buf: &metal::BufferRef,
+ data: &[f32],
+) {
+ unsafe {
+ std::ptr::copy_nonoverlapping(
+ data.as_ptr(),
+ buf.contents() as *mut f32,
+ data.len(),
+ );
+ }
+}
+
+fn read_buffer(
+ buf: &metal::BufferRef,
+ len: usize,
+) -> Vec<f32> {
+ let mut out = vec![0.0f32; len];
+ unsafe {
+ std::ptr::copy_nonoverlapping(
+ buf.contents() as *const f32,
+ out.as_mut_ptr(),
+ len,
+ );
+ }
+ out
+}
+
+fn zero_buffer(buf: &metal::BufferRef) {
+ unsafe {
+ std::ptr::write_bytes(buf.contents(), 0, buf.length() as usize);
+ }
+}
+
+fn ssd_prefill_cpu_reference(
+ suffix_len: usize,
+ num_heads: usize,
+ head_dim: usize,
+ state_dim: usize,
+ group_size: i32,
+ x_data: &[f32],
+ dt_raw_data: &[f32],
+ b_data: &[f32],
+ c_data: &[f32],
+ d_data: &[f32],
+ z_data: &[f32],
+ state_init: &[f32],
+ x_strides: [usize; 3],
+ dt_strides: [usize; 2],
+ cb_strides: [usize; 3],
+ state_strides: [usize; 3],
+) -> (Vec<f32>, Vec<f32>) {
+ let total_pairs = suffix_len * num_heads * head_dim;
+ let mut y_out = vec![0.0f32; total_pairs];
+ let mut state = state_init.to_vec();
+ let safe_group = group_size.max(1) as usize;
+
+ for h in 0..num_heads {
+ let group_idx = h / safe_group;
+ for dh in 0..head_dim {
+ let state_base = h * state_strides[0] + dh * state_strides[1];
+ for token in 0..suffix_len {
+ let x_idx =
+ token * x_strides[0] + h * x_strides[1] + dh * x_strides[2];
+ let dt_idx = token * dt_strides[0] + h * dt_strides[1];
+ let cb_base = token * cb_strides[0] + group_idx * cb_strides[1];
+
+ let x_val = x_data[x_idx];
+ let dt_raw = dt_raw_data[dt_idx];
+ let dt_val = softplus_f32(dt_raw);
+ let decay_val = (-dt_val).exp();
+ let dt_scaled_input = x_val;
+ let gate = silu_scalar(z_data[x_idx]);
+ let mut acc = d_data[h] * x_val;
+
+ for s in 0..state_dim {
+ let state_idx = state_base + s * state_strides[2];
+ let cb_idx = cb_base + s * cb_strides[2];
+ let b_coeff = b_data[cb_idx];
+ let c_coeff = c_data[cb_idx];
+ let new_state = decay_val * state[state_idx]
+ + dt_scaled_input * b_coeff;
+ state[state_idx] = new_state;
+ acc += new_state * c_coeff;
+ }
+
+ y_out[x_idx] = acc * gate;
+ }
+ }
+ }
+
+ (y_out, state)
+}
+
+struct SSDPrefillFixture {
+ suffix_len: usize,
+ num_heads: usize,
+ head_dim: usize,
+ state_dim: usize,
+ group_size: i32,
+ total_x: usize,
+ total_dt: usize,
+ total_cb: usize,
+ total_state: usize,
+ x_strides: [usize; 3],
+ dt_strides: [usize; 2],
+ cb_strides: [usize; 3],
+ state_strides: [usize; 3],
+ x_data: Vec<f32>,
+ dt_data: Vec<f32>,
+ b_data: Vec<f32>,
+ c_data: Vec<f32>,
+ d_data: Vec<f32>,
+ z_data: Vec<f32>,
+ state_init: Vec<f32>,
+}
+
+impl SSDPrefillFixture {
+ fn new() -> Self {
+ let suffix_len = 512usize;
+ let num_heads = 32usize;
+ let head_dim = 64usize;
+ let state_dim = 64usize;
+ let group_size = 1i32;
+ let group_count = num_heads / (group_size as usize);
+ let total_pairs = num_heads * head_dim;
+ let total_x = suffix_len * total_pairs;
+ let total_dt = suffix_len * num_heads;
+ let total_cb = suffix_len * group_count * state_dim;
+ let total_state = num_heads * head_dim * state_dim;
+
+ let x_data: Vec<f32> =
+ (0..total_x).map(|i| ((i % 17) as f32) * 0.01 - 0.05).collect();
+ let dt_data: Vec<f32> =
+ (0..total_dt).map(|i| ((i % 13) as f32) * 0.2 - 1.5).collect();
+ let b_data: Vec<f32> =
+ (0..total_cb).map(|i| ((i % 11) as f32) * 0.02 - 0.05).collect();
+ let c_data: Vec<f32> =
+ (0..total_cb).map(|i| ((i % 19) as f32) * 0.01 - 0.02).collect();
+ let d_data: Vec<f32> =
+ (0..num_heads).map(|i| ((i % 3) as f32) * 0.05 - 0.05).collect();
+ let z_data: Vec<f32> =
+ (0..total_x).map(|i| ((i % 23) as f32) * 0.02 - 0.1).collect();
+ let state_init: Vec<f32> =
+ (0..total_state).map(|i| ((i % 29) as f32) * 0.03 - 0.4).collect();
+
+ let x_strides = [num_heads * head_dim, head_dim, 1usize];
+ let dt_strides = [num_heads, 1usize];
+ let cb_strides = [group_count * state_dim, state_dim, 1usize];
+ let state_strides = [head_dim * state_dim, state_dim, 1usize];
+
+ Self {
+ suffix_len,
+ num_heads,
+ head_dim,
+ state_dim,
+ group_size,
+ total_x,
+ total_dt,
+ total_cb,
+ total_state,
+ x_strides,
+ dt_strides,
+ cb_strides,
+ state_strides,
+ x_data,
+ dt_data,
+ b_data,
+ c_data,
+ d_data,
+ z_data,
+ state_init,
+ }
+ }
+}
+
+fn run_prefill_kernel_mode(
+ ctx: &MTLContext,
+ kernel: &SSDPrefillKernel,
+ fixture: &SSDPrefillFixture,
+ mode: SSDPrefillMode,
+) -> (Vec<f32>, Vec<f32>, Option<(Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>)>) {
+ let device = &ctx.device;
+ let x_buf = device.new_buffer_with_data(
+ fixture.x_data.as_ptr() as *const _,
+ (fixture.total_x * 4) as u64,
+ STORAGE_MODE,
+ );
+ let dt_buf = device.new_buffer_with_data(
+ fixture.dt_data.as_ptr() as *const _,
+ (fixture.total_dt * 4) as u64,
+ STORAGE_MODE,
+ );
+ let b_buf = device.new_buffer_with_data(
+ fixture.b_data.as_ptr() as *const _,
+ (fixture.total_cb * 4) as u64,
+ STORAGE_MODE,
+ );
+ let c_buf = device.new_buffer_with_data(
+ fixture.c_data.as_ptr() as *const _,
+ (fixture.total_cb * 4) as u64,
+ STORAGE_MODE,
+ );
+ let d_buf = device.new_buffer_with_data(
+ fixture.d_data.as_ptr() as *const _,
+ (fixture.num_heads * 4) as u64,
+ STORAGE_MODE,
+ );
+ let z_buf = device.new_buffer_with_data(
+ fixture.z_data.as_ptr() as *const _,
+ (fixture.total_x * 4) as u64,
+ STORAGE_MODE,
+ );
+ let state_buf =
+ device.new_buffer((fixture.total_state * 4) as u64, STORAGE_MODE);
+ let y_buf = device.new_buffer((fixture.total_x * 4) as u64, STORAGE_MODE);
+
+ write_buffer(&state_buf, &fixture.state_init);
+ zero_buffer(&y_buf);
+
+ let args = SSDPrefillArguments {
+ x: &x_buf,
+ dt: &dt_buf,
+ b: &b_buf,
+ c: &c_buf,
+ d: &d_buf,
+ z: &z_buf,
+ state: &state_buf,
+ y: &y_buf,
+ suffix_len: fixture.suffix_len,
+ group_size: fixture.group_size,
+ state_size: fixture.state_dim as i32,
+ x_strides: fixture.x_strides,
+ dt_strides: fixture.dt_strides,
+ cb_strides: fixture.cb_strides,
+ state_strides: fixture.state_strides,
+ channels: fixture.num_heads,
+ head_dim: fixture.head_dim,
+ };
+
+ let command_buffer = ctx.command_queue.new_command_buffer();
+ let encoder = command_buffer.new_compute_command_encoder();
+ kernel.encode(encoder, args, mode).unwrap();
+ encoder.end_encoding();
+ command_buffer.commit();
+ command_buffer.wait_until_completed();
+
+ let y_vec = read_buffer(&y_buf, fixture.total_x);
+ let state_vec = read_buffer(&state_buf, fixture.total_state);
+ (y_vec, state_vec, None)
+}
+
+fn run_conv_scan_once(
+ ctx: &MTLContext,
+ kernel: &Conv1dScanKernel,
+ suffix_len: usize,
+ channels: usize,
+ kernel_size: i32,
+ tap_count: usize,
+ x_data: &[f32],
+ w_data: &[f32],
+ b_data: &[f32],
+ state_init: &[f32],
+ use_scratch: bool,
+ alias_io: bool,
+) -> (Vec<f32>, Vec<f32>) {
+ let device = &ctx.device;
+ let total_x = suffix_len * channels;
+ let total_w = channels * kernel_size as usize;
+ let total_state = channels * tap_count;
+
+ let y_buf = if alias_io {
+ device.new_buffer_with_data(
+ x_data.as_ptr() as *const _,
+ (total_x * size_of::<f32>()) as u64,
+ STORAGE_MODE,
+ )
+ } else {
+ let buf = device
+ .new_buffer((total_x * size_of::<f32>()) as u64, STORAGE_MODE);
+ zero_buffer(&buf);
+ buf
+ };
+ let w_buf = device.new_buffer_with_data(
+ w_data.as_ptr() as *const _,
+ (total_w * size_of::<f32>()) as u64,
+ STORAGE_MODE,
+ );
+ let b_buf = device.new_buffer_with_data(
+ b_data.as_ptr() as *const _,
+ (channels * size_of::<f32>()) as u64,
+ STORAGE_MODE,
+ );
+ let state_buf = device
+ .new_buffer((total_state * size_of::<f32>()) as u64, STORAGE_MODE);
+ let scratch_buf =
+ if use_scratch && tap_count > 0 {
+ Some(device.new_buffer(
+ (total_state * size_of::<f32>()) as u64,
+ STORAGE_MODE,
+ ))
+ } else {
+ None
+ };
+
+ write_buffer(&state_buf, state_init);
+ if let Some(ref scratch) = scratch_buf {
+ zero_buffer(scratch);
+ }
+
+ let padded_len = tap_count + suffix_len;
+ let padded_buf = device.new_buffer(
+ (padded_len * channels * size_of::<f32>()) as u64,
+ STORAGE_MODE,
+ );
+ {
+ let mut host = vec![0.0f32; padded_len * channels];
+ for tap in 0..tap_count {
+ for ch in 0..channels {
+ host[tap * channels + ch] = state_init[ch * tap_count + tap];
+ }
+ }
+ for token in 0..suffix_len {
+ for ch in 0..channels {
+ host[(tap_count + token) * channels + ch] =
+ x_data[token * channels + ch];
+ }
+ }
+ write_buffer(&padded_buf, &host);
+ }
+
+ let args = Conv1dScanArguments {
+ padded: &padded_buf,
+ w: &w_buf,
+ b: Some(&b_buf),
+ x_out: &y_buf,
+ b_out: &y_buf,
+ c_out: &y_buf,
+ state_out: scratch_buf.as_ref().unwrap_or(&state_buf),
+ suffix_len,
+ kernel_size,
+ row_stride: channels,
+ state_stride: tap_count,
+ channels,
+ inner_dim: channels,
+ proj_dim: 0,
+ };
+
+ let command_buffer = ctx.command_queue.new_command_buffer();
+ let encoder = command_buffer.new_compute_command_encoder();
+ kernel.encode(encoder, args).unwrap();
+ encoder.end_encoding();
+
+ if let Some(ref scratch) = scratch_buf {
+ let bytes = (channels * tap_count * size_of::<f32>()) as u64;
+ if bytes > 0 {
+ let blit = command_buffer.new_blit_command_encoder();
+ blit.copy_from_buffer(scratch, 0, &state_buf, 0, bytes);
+ blit.end_encoding();
+ }
+ }
+
+ command_buffer.commit();
+ command_buffer.wait_until_completed();
+
+ let y_vec = read_buffer(&y_buf, total_x);
+ let state_vec = read_buffer(&state_buf, total_state);
+ (y_vec, state_vec)
+}
+
+fn assert_deterministic_for_mode(mode: SSDPrefillMode) {
+ let Some(ctx) = create_context() else {
+ eprintln!("Skipping SSD prefill determinism test: no Metal device");
+ return;
+ };
+ let kernel = SSDPrefillKernel::new(&ctx, KernelDataType::Float32).unwrap();
+ let fixture = SSDPrefillFixture::new();
+
+ let (y_a, state_a, _) =
+ run_prefill_kernel_mode(&ctx, &kernel, &fixture, mode);
+ let (y_b, state_b, _) =
+ run_prefill_kernel_mode(&ctx, &kernel, &fixture, mode);
+
+ assert_eq!(y_a, y_b, "Prefill outputs differ in {:?} mode", mode);
+ assert_eq!(state_a, state_b, "Prefill states differ in {:?} mode", mode);
+}
+
+fn assert_matches_cpu_reference(mode: SSDPrefillMode) {
+ let Some(ctx) = create_context() else {
+ eprintln!("Skipping SSD prefill reference test: no Metal device");
+ return;
+ };
+ let kernel = SSDPrefillKernel::new(&ctx, KernelDataType::Float32).unwrap();
+ let fixture = SSDPrefillFixture::new();
+
+ let (y_ref, state_ref) = ssd_prefill_cpu_reference(
+ fixture.suffix_len,
+ fixture.num_heads,
+ fixture.head_dim,
+ fixture.state_dim,
+ fixture.group_size,
+ &fixture.x_data,
+ &fixture.dt_data,
+ &fixture.b_data,
+ &fixture.c_data,
+ &fixture.d_data,
+ &fixture.z_data,
+ &fixture.state_init,
+ fixture.x_strides,
+ fixture.dt_strides,
+ fixture.cb_strides,
+ fixture.state_strides,
+ );
+
+ let (y_gpu, state_gpu, _) =
+ run_prefill_kernel_mode(&ctx, &kernel, &fixture, mode);
+
+ let tolerance = 5e-5f32;
+ let mut max_y_diff = 0.0f32;
+ let mut max_y_idx = 0usize;
+ for (idx, (&lhs, &rhs)) in y_gpu.iter().zip(&y_ref).enumerate() {
+ let diff = (lhs - rhs).abs();
+ if diff > max_y_diff {
+ max_y_diff = diff;
+ max_y_idx = idx;
+ }
+ }
+ assert!(
+ max_y_diff <= tolerance,
+ "Prefill outputs diverge in {:?} mode at idx {max_y_idx}: metal={} cpu={} (diff {max_y_diff})",
+ mode,
+ y_gpu[max_y_idx],
+ y_ref[max_y_idx]
+ );
+
+ let mut max_state_diff = 0.0f32;
+ let mut max_state_idx = 0usize;
+ for (idx, (&lhs, &rhs)) in state_gpu.iter().zip(&state_ref).enumerate() {
+ let diff = (lhs - rhs).abs();
+ if diff > max_state_diff {
+ max_state_diff = diff;
+ max_state_idx = idx;
+ }
+ }
+ assert!(
+ max_state_diff <= tolerance,
+ "Prefill states diverge in {:?} mode at idx {max_state_idx}: metal={} cpu={} (diff {max_state_diff})",
+ mode,
+ state_gpu[max_state_idx],
+ state_ref[max_state_idx]
+ );
+}
+
+#[test]
+fn ssd_prefill_sequential_is_deterministic() {
+ assert_deterministic_for_mode(SSDPrefillMode::Sequential);
+}
+
+#[test]
+fn ssd_prefill_single_pass_is_deterministic() {
+ assert_deterministic_for_mode(SSDPrefillMode::SinglePass);
+}
+
+#[test]
+fn ssd_prefill_sequential_matches_cpu_reference() {
+ assert_matches_cpu_reference(SSDPrefillMode::Sequential);
+}
+
+#[test]
+fn ssd_prefill_single_pass_matches_cpu_reference() {
+ assert_matches_cpu_reference(SSDPrefillMode::SinglePass);
+}
+
+#[test]
+fn conv1d_scan_is_deterministic() {
+ let Some(ctx) = create_context() else {
+ eprintln!("Skipping conv1d scan determinism test: no Metal device");
+ return;
+ };
+ let activation = Activation::Identity;
+ let kernel =
+ Conv1dScanKernel::new(&ctx, KernelDataType::Float32, &activation)
+ .unwrap();
+
+ let suffix_len = 192usize;
+ let channels = 8usize;
+ let kernel_size = 5i32;
+ let tap_count = (kernel_size - 1) as usize;
+
+ let total_x = suffix_len * channels;
+ let total_state = channels * tap_count;
+
+ let x_data: Vec<f32> =
+ (0..total_x).map(|i| ((i % 31) as f32) * 0.02 - 0.3).collect();
+ let w_data: Vec<f32> = (0..(channels * kernel_size as usize))
+ .map(|i| ((i % 17) as f32) * 0.01 - 0.04)
+ .collect();
+ let b_data: Vec<f32> =
+ (0..channels).map(|i| ((i % 5) as f32) * 0.03 - 0.07).collect();
+ let state_init: Vec<f32> =
+ (0..total_state).map(|i| ((i % 23) as f32) * 0.02 - 0.1).collect();
+
+ let use_scratch = tap_count > 0 && suffix_len > 1;
+
+ for &alias_io in &[false, true] {
+ let first = run_conv_scan_once(
+ &ctx,
+ &kernel,
+ suffix_len,
+ channels,
+ kernel_size,
+ tap_count,
+ &x_data,
+ &w_data,
+ &b_data,
+ &state_init,
+ use_scratch,
+ alias_io,
+ );
+ let second = run_conv_scan_once(
+ &ctx,
+ &kernel,
+ suffix_len,
+ channels,
+ kernel_size,
+ tap_count,
+ &x_data,
+ &w_data,
+ &b_data,
+ &state_init,
+ use_scratch,
+ alias_io,
+ );
+
+ assert_eq!(
+ first.0, second.0,
+ "Conv outputs differ (alias_io={alias_io})"
+ );
+ assert_eq!(
+ first.1, second.1,
+ "Conv states differ (alias_io={alias_io})"
+ );
+ }
+}
diff --git a/crates/uzu/tests/ssm_update_test.rs b/crates/uzu/tests/ssm_update_test.rs
new file mode 100644
index 000000000..fa4b40986
--- /dev/null
+++ b/crates/uzu/tests/ssm_update_test.rs
@@ -0,0 +1,443 @@
+#![cfg(any(target_os = "macos"))]
+
+use half::bf16;
+use metal::MTLResourceOptions;
+use uzu::backends::metal::{
+ KernelDataType, MTLContext,
+ kernel::ssm::{
+ SSDUpdateArguments, SSDUpdateKernel, SSMUpdateArguments,
+ SSMUpdateKernel,
+ },
+};
+fn ssm_update_ref_bf16(
+ x: &[bf16],
+ dt: &[bf16],
+ a: &[bf16],
+ b: &[bf16],
+ c: &[bf16],
+ d: &[bf16],
+ z: &[bf16],
+ state: &[bf16],
+ bsz: usize,
+ h: usize,
+) -> (Vec<bf16>, Vec<bf16>) {
+ let n: usize = 16;
+ let mut y = vec![bf16::from_f32(0.0); bsz * h];
+ let mut next_state = vec![bf16::from_f32(0.0); bsz * h * n];
+ for bb in 0..bsz {
+ for ch in 0..h {
+ let idx = bb * h + ch;
+ let vx = x[idx].to_f32();
+ let sig = 1.0 / (1.0 + (-vx.abs()).exp());
+ let this_x = if vx < 0.0 {
+ (1.0 - sig) * vx
+ } else {
+ sig * vx
+ };
+ let vz = z[idx].to_f32();
+ let sigz = 1.0 / (1.0 + (-vz.abs()).exp());
+ let this_z = if vz < 0.0 {
+ (1.0 - sigz) * vz
+ } else {
+ sigz * vz
+ };
+ let delta = (1.0 + dt[idx].to_f32().exp()).ln();
+ let cb_offset = bb * n;
+ let state_offset = idx * n;
+ let mut acc = 0.0f32;
+ for i in 0..n {
+ let new_s = state[state_offset + i].to_f32()
+ * (a[i].to_f32() * delta).exp()
+ + b[cb_offset + i].to_f32() * delta * this_x;
+ next_state[state_offset + i] = bf16::from_f32(new_s);
+ acc += new_s * c[cb_offset + i].to_f32();
+ }
+ acc += d[ch].to_f32() * this_x;
+ acc *= this_z;
+ y[idx] = bf16::from_f32(acc);
+ }
+ }
+ (y, next_state)
+}
+
+fn softplus_f32(x: f32) -> f32 {
+ if x > 20.0 {
+ x
+ } else {
+ (1.0 + x.exp()).ln()
+ }
+}
+
+fn ssd_update_no_z_ref_bf16(
+ x: &[bf16],
+ dt_raw: &[bf16],
+ b: &[bf16],
+ c: &[bf16],
+ d: &[bf16],
+ state: &[bf16],
+ bsz: usize,
+ h: usize,
+ dh: usize,
+ g: usize,
+ n: usize,
+) -> (Vec<bf16>, Vec<bf16>) {
+ let group_size = h / g;
+ let mut y = vec![bf16::from_f32(0.0); bsz * h * dh];
+ let mut next_state = vec![bf16::from_f32(0.0); bsz * h * dh * n];
+ for bb in 0..bsz {
+ for hh in 0..h {
+ for ddh in 0..dh {
+ let x_idx = bb * h * dh + hh * dh + ddh;
+ let dt_idx = bb * h + hh;
+ let cb_idx0 = bb * g * n + (hh / group_size) * n;
+ let state_idx0 = (bb * h * dh + hh * dh + ddh) * n;
+ let this_x = x[x_idx].to_f32();
+ let dt_raw_val = dt_raw[dt_idx].to_f32();
+ let this_dt = softplus_f32(dt_raw_val);
+ let this_decay = (-this_dt).exp();
+ let this_d = d[hh].to_f32();
+ let dt_safe = this_dt.max(1e-6);
+ let normalized_x = this_x / dt_safe;
+ let dt_scaled_input = normalized_x * this_dt;
+ let mut acc = 0.0f32;
+ for i in 0..n {
+ let s_old = state[state_idx0 + i].to_f32();
+ let new_s = s_old * this_decay
+ + b[cb_idx0 + i].to_f32() * dt_scaled_input;
+ next_state[state_idx0 + i] = bf16::from_f32(new_s);
+ acc += new_s * c[cb_idx0 + i].to_f32();
+ }
+ acc += this_d * this_x;
+ y[x_idx] = bf16::from_f32(acc);
+ }
+ }
+ }
+ (y, next_state)
+}
+
+fn ssd_update_ref_bf16(
+ x: &[bf16],
+ dt_raw: &[bf16],
+ b: &[bf16],
+ c: &[bf16],
+ d: &[bf16],
+ z: &[bf16],
+ state: &[bf16],
+ bsz: usize,
+ h: usize,
+ dh: usize,
+ g: usize,
+ n: usize,
+) -> (Vec<bf16>, Vec<bf16>) {
+ let group_size = h / g;
+ let mut y = vec![bf16::from_f32(0.0); bsz * h * dh];
+ let mut next_state = vec![bf16::from_f32(0.0); bsz * h * dh * n];
+ for bb in 0..bsz {
+ for hh in 0..h {
+ for ddh in 0..dh {
+ let x_idx = bb * h * dh + hh * dh + ddh;
+ let dt_idx = bb * h + hh;
+ let cb_idx0 = bb * g * n + (hh / group_size) * n;
+ let state_idx0 = (bb * h * dh + hh * dh + ddh) * n;
+ let this_x = x[x_idx].to_f32();
+ let dt_raw_val = dt_raw[dt_idx].to_f32();
+ let this_dt = softplus_f32(dt_raw_val);
+ let this_decay = (-this_dt).exp();
+ let this_d = d[hh].to_f32();
+ let dt_safe = this_dt.max(1e-6);
+ let normalized_x = this_x / dt_safe;
+ let dt_scaled_input = normalized_x * this_dt;
+ let vz = z[x_idx].to_f32();
+ let sigz = 1.0 / (1.0 + (-vz.abs()).exp());
+ let this_z = if vz < 0.0 {
+ (1.0 - sigz) * vz
+ } else {
+ sigz * vz
+ };
+ let mut acc = 0.0f32;
+ for i in 0..n {
+ let s_old = state[state_idx0 + i].to_f32();
+ let new_s = s_old * this_decay
+ + b[cb_idx0 + i].to_f32() * dt_scaled_input;
+ next_state[state_idx0 + i] = bf16::from_f32(new_s);
+ acc += new_s * c[cb_idx0 + i].to_f32();
+ }
+ acc += this_d * this_x;
+ acc *= this_z;
+ y[x_idx] = bf16::from_f32(acc);
+ }
+ }
+ }
+ (y, next_state)
+}
+
+fn create_context() -> Option<MTLContext> {
+ let device = metal::Device::system_default()?;
+ let command_queue = device.new_command_queue();
+ MTLContext::new(device, command_queue).ok()
+}
+
+#[test]
+fn ssm_update_bf16() {
+ let Some(ctx) = create_context() else {
+ eprintln!("Skipping: no Metal device");
+ return;
+ };
+ let bsz = 2usize;
+ let h = 4usize;
+ let n = 16usize;
+
+ let x: Vec<bf16> = (0..bsz * h)
+ .map(|i| bf16::from_f32(((i % 7) as f32) * 0.1 - 0.2))
+ .collect();
+ let dt: Vec<bf16> =
+ (0..bsz * h).map(|i| bf16::from_f32(((i % 5) as f32) * 0.03)).collect();
+ let a: Vec<bf16> = (0..n)
+ .map(|i| bf16::from_f32(((i % 11) as f32) * 0.02 - 0.1))
+ .collect();
+ let b: Vec<bf16> = (0..bsz * n)
+ .map(|i| bf16::from_f32(((i % 13) as f32) * 0.01))
+ .collect();
+ let c: Vec<bf16> = (0..bsz * n)
+ .map(|i| bf16::from_f32(((i % 17) as f32) * 0.015))
+ .collect();
+ let d: Vec<bf16> =
+ (0..h).map(|i| bf16::from_f32(((i % 3) as f32) * 0.05)).collect();
+ let z: Vec<bf16> = (0..bsz * h)
+ .map(|i| bf16::from_f32(((i % 7) as f32) * 0.1 - 0.1))
+ .collect();
+ let state: Vec<bf16> = (0..bsz * h * n)
+ .map(|i| bf16::from_f32(((i % 23) as f32) * 0.01 - 0.05))
+ .collect();
+
+ let (y_exp, ns_exp) =
+ ssm_update_ref_bf16(&x, &dt, &a, &b, &c, &d, &z, &state, bsz, h);
+ let y_exp_f32: Vec<f32> = y_exp.iter().map(|&v| v.to_f32()).collect();
+ let ns_exp_f32: Vec<f32> = ns_exp.iter().map(|&v| v.to_f32()).collect();
+
+ let x_buf = ctx.device.new_buffer_with_data(
+ x.as_ptr() as *const _,
+ (x.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let dt_buf = ctx.device.new_buffer_with_data(
+ dt.as_ptr() as *const _,
+ (dt.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let a_buf = ctx.device.new_buffer_with_data(
+ a.as_ptr() as *const _,
+ (a.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let b_buf = ctx.device.new_buffer_with_data(
+ b.as_ptr() as *const _,
+ (b.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let c_buf = ctx.device.new_buffer_with_data(
+ c.as_ptr() as *const _,
+ (c.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let d_buf = ctx.device.new_buffer_with_data(
+ d.as_ptr() as *const _,
+ (d.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let z_buf = ctx.device.new_buffer_with_data(
+ z.as_ptr() as *const _,
+ (z.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let s_buf = ctx.device.new_buffer_with_data(
+ state.as_ptr() as *const _,
+ (state.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let y_buf = ctx.device.new_buffer(
+ (bsz * h * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let ns_buf = ctx.device.new_buffer(
+ (bsz * h * n * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+
+ let kernel = SSMUpdateKernel::new(&ctx, KernelDataType::BFloat16).unwrap();
+ let cb_ref = ctx.command_queue.new_command_buffer();
+ let cb = cb_ref.to_owned();
+ let enc = cb.new_compute_command_encoder();
+ kernel
+ .encode(
+ &enc,
+ SSMUpdateArguments {
+ x: &x_buf,
+ dt: &dt_buf,
+ a: &a_buf,
+ b: &b_buf,
+ c: &c_buf,
+ d: &d_buf,
+ z: &z_buf,
+ state: &s_buf,
+ y: &y_buf,
+ next_state: &ns_buf,
+ batch_size: bsz,
+ channels: h,
+ },
+ )
+ .unwrap();
+ enc.end_encoding();
+ cb_ref.commit();
+ cb_ref.wait_until_completed();
+
+ let y_ptr = y_buf.contents() as *const bf16;
+ let y_out = unsafe { std::slice::from_raw_parts(y_ptr, bsz * h) };
+ let y_out_f32: Vec<f32> = y_out.iter().map(|&v| v.to_f32()).collect();
+ let ns_ptr = ns_buf.contents() as *const bf16;
+ let ns_out = unsafe { std::slice::from_raw_parts(ns_ptr, bsz * h * n) };
+ let ns_out_f32: Vec<f32> = ns_out.iter().map(|&v| v.to_f32()).collect();
+ let tol = 2e-2;
+ for (i, (a, b)) in y_out_f32.iter().zip(y_exp_f32.iter()).enumerate() {
+ assert!((a - b).abs() < tol, "y {} {} {}", i, a, b);
+ }
+ for (i, (a, b)) in ns_out_f32.iter().zip(ns_exp_f32.iter()).enumerate() {
+ assert!((a - b).abs() < tol, "ns {} {} {}", i, a, b);
+ }
+}
+
+#[test]
+fn ssd_update_with_z_bf16() {
+ let Some(ctx) = create_context() else {
+ eprintln!("Skipping: no Metal device");
+ return;
+ };
+ let bsz = 1usize;
+ let h = 4usize;
+ let dh = 3usize;
+ let g = 2usize;
+ let n = 8usize;
+
+ let x: Vec<bf16> = (0..bsz * h * dh)
+ .map(|i| bf16::from_f32(((i % 7) as f32) * 0.1 - 0.2))
+ .collect();
+ let z: Vec<bf16> = (0..bsz * h * dh)
+ .map(|i| bf16::from_f32(((i % 5) as f32) * 0.1 - 0.1))
+ .collect();
+ let dt: Vec<bf16> = (0..bsz * h)
+ .map(|i| bf16::from_f32(((i % 5) as f32) * 0.3 - 1.0))
+ .collect();
+ let b: Vec<bf16> = (0..bsz * g * n)
+ .map(|i| bf16::from_f32(((i % 11) as f32) * 0.02 - 0.05))
+ .collect();
+ let c: Vec<bf16> = (0..bsz * g * n)
+ .map(|i| bf16::from_f32(((i % 13) as f32) * 0.015))
+ .collect();
+ let d: Vec<bf16> =
+ (0..h).map(|i| bf16::from_f32(((i % 3) as f32) * 0.05)).collect();
+ let state: Vec<bf16> = (0..bsz * h * dh * n)
+ .map(|i| bf16::from_f32(((i % 23) as f32) * 0.01 - 0.05))
+ .collect();
+
+ let (y_exp, ns_exp) =
+ ssd_update_ref_bf16(&x, &dt, &b, &c, &d, &z, &state, bsz, h, dh, g, n);
+ let y_exp_f32: Vec<f32> = y_exp.iter().map(|&v| v.to_f32()).collect();
+ let ns_exp_f32: Vec<f32> = ns_exp.iter().map(|&v| v.to_f32()).collect();
+
+ let x_strides = [h * dh, dh, 1usize];
+ let dt_strides = [h, 1usize];
+ let cb_strides = [g * n, n, 1usize];
+ let state_strides = [h * dh * n, dh * n, n, 1usize];
+
+ let x_buf = ctx.device.new_buffer_with_data(
+ x.as_ptr() as *const _,
+ (x.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let dt_buf = ctx.device.new_buffer_with_data(
+ dt.as_ptr() as *const _,
+ (dt.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let b_buf = ctx.device.new_buffer_with_data(
+ b.as_ptr() as *const _,
+ (b.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let c_buf = ctx.device.new_buffer_with_data(
+ c.as_ptr() as *const _,
+ (c.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let d_buf = ctx.device.new_buffer_with_data(
+ d.as_ptr() as *const _,
+ (d.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let z_buf = ctx.device.new_buffer_with_data(
+ z.as_ptr() as *const _,
+ (z.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let state_buf = ctx.device.new_buffer_with_data(
+ state.as_ptr() as *const _,
+ (state.len() * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let y_buf = ctx.device.new_buffer(
+ (bsz * h * dh * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+ let ns_buf = ctx.device.new_buffer(
+ (bsz * h * dh * n * std::mem::size_of::<bf16>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ );
+
+ let kernel = SSDUpdateKernel::new(&ctx, KernelDataType::BFloat16).unwrap();
+ let cb_ref = ctx.command_queue.new_command_buffer();
+ let cb = cb_ref.to_owned();
+ let enc = cb.new_compute_command_encoder();
+ kernel
+ .encode(
+ &enc,
+ SSDUpdateArguments {
+ x: &x_buf,
+ dt: &dt_buf,
+ b: &b_buf,
+ c: &c_buf,
+ d: &d_buf,
+ z: &z_buf,
+ state: &state_buf,
+ y: &y_buf,
+ next_state: &ns_buf,
+ group_size: (h / g) as i32,
+ state_size: n as i32,
+ x_strides,
+ dt_strides,
+ cb_strides,
+ state_strides,
+ b_size: bsz,
+ h_size: h,
+ dh_size: dh,
+ },
+ )
+ .unwrap();
+ enc.end_encoding();
+ cb_ref.commit();
+ cb_ref.wait_until_completed();
+
+ let y_ptr = y_buf.contents() as *const bf16;
+ let y_out = unsafe { std::slice::from_raw_parts(y_ptr, bsz * h * dh) };
+ let y_out_f32: Vec<f32> = y_out.iter().map(|&v| v.to_f32()).collect();
+ let ns_ptr = ns_buf.contents() as *const bf16;
+ let ns_out =
+ unsafe { std::slice::from_raw_parts(ns_ptr, bsz * h * dh * n) };
+ let ns_out_f32: Vec<f32> = ns_out.iter().map(|&v| v.to_f32()).collect();
+ let tol = 2e-2;
+ for (i, (a, b)) in y_out_f32.iter().zip(y_exp_f32.iter()).enumerate() {
+ assert!((a - b).abs() < tol, "y {} {} {}", i, a, b);
+ }
+ for (i, (a, b)) in ns_out_f32.iter().zip(ns_exp_f32.iter()).enumerate() {
+ assert!((a - b).abs() < tol, "ns {} {} {}", i, a, b);
+ }
+}
diff --git a/crates/uzu/tests/text_session_test.rs b/crates/uzu/tests/text_session_test.rs
index 3a0d4c24b..f531da86e 100644
--- a/crates/uzu/tests/text_session_test.rs
+++ b/crates/uzu/tests/text_session_test.rs
@@ -3,11 +3,8 @@ use std::path::PathBuf;
use uzu::session::{
Session,
- config::{DecodingConfig, RunConfig, SpeculatorConfig},
- parameter::{
- ContextLength, ContextMode, PrefillStepSize, SamplingMethod,
- SamplingPolicy, SamplingSeed,
- },
+ config::{DecodingConfig, RunConfig},
+ parameter::SamplingSeed,
types::{Input, Message, Output},
};
@@ -16,14 +13,7 @@ fn build_model_path() -> PathBuf {
}
fn build_decoding_config() -> DecodingConfig {
- DecodingConfig::new(
- ContextMode::default(),
- ContextLength::default(),
- PrefillStepSize::default(),
- SpeculatorConfig::default(),
- SamplingSeed::Custom(42),
- true,
- )
+ DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(42))
}
#[test]
@@ -53,23 +43,25 @@ fn run(
let output = session
.run(
input,
- RunConfig::new(
- tokens_limit,
- true,
- SamplingPolicy::Custom {
- value: SamplingMethod::Greedy,
- },
- ),
+ RunConfig::default().tokens_limit(tokens_limit),
Some(|_: Output| {
return true;
}),
)
.unwrap();
+ let empty_response = String::from("None");
+
println!("-------------------------");
- println!("{:#?}", output.text.parsed.chain_of_thought);
+ println!(
+ "{}",
+ output.text.parsed.chain_of_thought.unwrap_or(empty_response.clone())
+ );
println!("-------------------------");
- println!("{:#?}", output.text.parsed.response);
+ println!(
+ "{}",
+ output.text.parsed.response.unwrap_or(empty_response.clone())
+ );
println!("-------------------------");
println!("{:#?}", output.stats);
println!("-------------------------");