Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

quantized untied support

eugene49101b1ccde0
diff --git a/.gitignore b/.gitignore
index 5d0a69756..afdab63c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,6 @@ external/
# Local-only dev example
crates/uzu/examples/quick_chat.rs
+
+# Local-only dev example: structured chat output validator
+crates/uzu/examples/chat_output_validator.rs
diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding.rs b/crates/uzu/src/backends/metal/encodable_block/embedding.rs
index 1b22fde31..f80562f35 100644
--- a/crates/uzu/src/backends/metal/encodable_block/embedding.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/embedding.rs
@@ -46,7 +46,7 @@ pub struct QuantizedEmbeddingLookup {
}
impl QuantizedEmbeddingLookup {
- pub fn new(
+ pub fn new_tied(
mtl_context: &MTLContext,
data_type: DataType,
vocab_size: usize,
@@ -55,6 +55,59 @@ impl QuantizedEmbeddingLookup {
mode: QuantizationMode,
input_scale: f32,
parameter_tree: &ParameterTree<Rc<MTLContext>>,
+ ) -> Result<Self, QuantizedEmbeddingError> {
+ Self::new_with_names(
+ mtl_context,
+ data_type,
+ vocab_size,
+ model_dim,
+ group_size,
+ mode,
+ input_scale,
+ "weights",
+ "scales",
+ "biases",
+ parameter_tree,
+ )
+ }
+
+ pub fn new_untied_input(
+ mtl_context: &MTLContext,
+ data_type: DataType,
+ vocab_size: usize,
+ model_dim: usize,
+ group_size: usize,
+ mode: QuantizationMode,
+ input_scale: f32,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+ ) -> Result<Self, QuantizedEmbeddingError> {
+ Self::new_with_names(
+ mtl_context,
+ data_type,
+ vocab_size,
+ model_dim,
+ group_size,
+ mode,
+ input_scale,
+ "input_weights",
+ "input_scales",
+ "input_biases",
+ parameter_tree,
+ )
+ }
+
+ fn new_with_names(
+ mtl_context: &MTLContext,
+ data_type: DataType,
+ vocab_size: usize,
+ model_dim: usize,
+ group_size: usize,
+ mode: QuantizationMode,
+ input_scale: f32,
+ weights_name: &str,
+ scales_name: &str,
+ biases_name: &str,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
) -> Result<Self, QuantizedEmbeddingError> {
let packing_divisor = mode.packing_divisor();
@@ -62,15 +115,12 @@ impl QuantizedEmbeddingLookup {
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
- )))
- })?,
- };
+ let mut weights = parameter_tree.leaf(weights_name).map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load {weights_name}: {:?}",
+ e
+ )))
+ })?;
if weights.data_type() != mode.storage_type() {
return Err(QuantizedEmbeddingError::MetalError(
@@ -83,15 +133,12 @@ impl QuantizedEmbeddingLookup {
}
// 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
- )))
- })?,
- };
+ let mut scales = parameter_tree.leaf(scales_name).map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load {scales_name}: {:?}",
+ e
+ )))
+ })?;
// Validate shapes and types
let num_groups = (model_dim + group_size - 1) / group_size;
@@ -121,16 +168,13 @@ impl QuantizedEmbeddingLookup {
));
}
- // 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"))
- {
+ // Load or create biases buffer [vocab_size, num_groups]
+ let biases_buffer: MTLBuffer = match parameter_tree.leaf(biases_name) {
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 [{}, {}]",
+ "Embedding lookup biases shape mismatch: got {:?}, expected [{}, {}]",
deq_biases.shape(),
vocab_size,
num_groups
@@ -241,36 +285,79 @@ pub struct QuantizedEmbeddingReadout {
}
impl QuantizedEmbeddingReadout {
- pub fn new(
+ pub fn new_tied(
+ 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> {
+ Self::new_with_names(
+ mtl_context,
+ data_type,
+ vocab_size,
+ model_dim,
+ group_size,
+ mode,
+ "weights",
+ "scales",
+ "biases",
+ parameter_tree,
+ )
+ }
+
+ pub fn new_untied_output(
+ 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> {
+ Self::new_with_names(
+ mtl_context,
+ data_type,
+ vocab_size,
+ model_dim,
+ group_size,
+ mode,
+ "output_weights",
+ "output_scales",
+ "output_biases",
+ parameter_tree,
+ )
+ }
+
+ fn new_with_names(
mtl_context: &MTLContext,
data_type: DataType,
vocab_size: usize,
model_dim: usize,
group_size: usize,
mode: QuantizationMode,
+ weights_name: &str,
+ scales_name: &str,
+ biases_name: &str,
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
- )))
- })?,
- };
+ let mut weights = parameter_tree.leaf(weights_name).map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load {weights_name}: {:?}",
+ 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
- )))
- })?,
- };
+ let mut scales = parameter_tree.leaf(scales_name).map_err(|e| {
+ QuantizedEmbeddingError::MetalError(MTLError::Generic(format!(
+ "Failed to load {scales_name}: {:?}",
+ e
+ )))
+ })?;
// Validate shapes
let num_groups = (model_dim + group_size - 1) / group_size;
@@ -306,10 +393,7 @@ impl QuantizedEmbeddingReadout {
}
// 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"))
- {
+ let biases_buffer: MTLBuffer = match parameter_tree.leaf(biases_name) {
Ok(mut deq_biases) => {
if deq_biases.shape() != [vocab_size, num_groups] {
return Err(QuantizedEmbeddingError::MetalError(
diff --git a/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs b/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs
index 79edd8901..12f439f33 100644
--- a/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs
@@ -479,7 +479,35 @@ pub fn embed_block(
.subtree("embedding")
.expect("Failed to get embedding subtree");
- let block = QuantizedEmbeddingLookup::new(
+ let block = QuantizedEmbeddingLookup::new_tied(
+ context,
+ data_type,
+ config.vocab_size,
+ config.model_dim,
+ *group_size,
+ *embedding_quantization_mode,
+ input_scale,
+ &embeddings_tree,
+ )
+ .expect("Failed to create quantized embedding lookup kernel");
+
+ Box::new(block)
+ },
+ EmbeddingConfig::MLXQuantizedUntied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ let data_type: DataType =
+ config.output_norm_config.scale_precision.into();
+ let input_scale =
+ config.embedding_config.common().input_scale.unwrap_or(1.0);
+
+ let embeddings_tree = parameter_tree
+ .subtree("embedding")
+ .expect("Failed to get embedding subtree");
+
+ let block = QuantizedEmbeddingLookup::new_untied_input(
context,
data_type,
config.vocab_size,
@@ -614,7 +642,7 @@ pub fn readout_block(
.subtree("embedding")
.expect("Failed to get embedding subtree");
- let block = QuantizedEmbeddingReadout::new(
+ let block = QuantizedEmbeddingReadout::new_untied_output(
context,
data_type,
config.vocab_size,
@@ -704,7 +732,32 @@ pub fn readout_block(
.subtree("embedding")
.expect("Failed to get embedding subtree");
- let block = QuantizedEmbeddingReadout::new(
+ let block = QuantizedEmbeddingReadout::new_tied(
+ 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::MLXQuantizedUntied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ let data_type: DataType =
+ config.output_norm_config.scale_precision.into();
+
+ let embeddings_tree = parameter_tree
+ .subtree("embedding")
+ .expect("Failed to get embedding subtree");
+
+ let block = QuantizedEmbeddingReadout::new_untied_output(
context,
data_type,
config.vocab_size,
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
index 234934391..b64f1dc3d 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
@@ -38,6 +38,20 @@ pub enum EmbeddingsBuffers {
/// [vocab_size, num_groups]
output_biases: ArrayCell,
},
+ MLXQuantizedUntied {
+ /// [vocab_size, model_dim/pack]
+ packed_input_weights: ArrayCell,
+ /// [vocab_size, num_groups]
+ input_scales: ArrayCell,
+ /// [vocab_size, num_groups]
+ input_biases: ArrayCell,
+ /// [vocab_size, model_dim/pack]
+ packed_output_weights: ArrayCell,
+ /// [vocab_size, num_groups]
+ output_scales: ArrayCell,
+ /// [vocab_size, num_groups]
+ output_biases: ArrayCell,
+ },
}
impl EmbeddingsBuffers {
@@ -160,6 +174,50 @@ impl EmbeddingsBuffers {
),
}
},
+ EmbeddingConfig::MLXQuantizedUntied {
+ group_size,
+ embedding_quantization_mode,
+ ..
+ } => {
+ let [vocab_size, model_dim] =
+ model_shape.quantized_embeddings_weights_shape();
+ let num_groups = model_dim / group_size;
+ let pack = embedding_quantization_mode.packing_divisor();
+ Self::MLXQuantizedUntied {
+ packed_input_weights: RefCell::new(
+ context.array_uninitialized(
+ &[vocab_size, model_dim / pack],
+ embedding_quantization_mode.storage_type(),
+ ),
+ ),
+ input_scales: RefCell::new(context.array_uninitialized(
+ &[vocab_size, num_groups],
+ model_shape.activation_data_type(),
+ )),
+ input_biases: RefCell::new(context.array_uninitialized(
+ &[vocab_size, num_groups],
+ model_shape.activation_data_type(),
+ )),
+ packed_output_weights: RefCell::new(
+ context.array_uninitialized(
+ &[vocab_size, model_dim / pack],
+ 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(),
+ ),
+ ),
+ }
+ },
}
}
}
@@ -216,6 +274,27 @@ impl EmbeddingsBuffers {
buffer.borrow_mut().copy_from_array(&view);
}
},
+ EmbeddingsBuffers::MLXQuantizedUntied {
+ packed_input_weights,
+ input_scales,
+ input_biases,
+ packed_output_weights,
+ output_scales,
+ output_biases,
+ } => {
+ let mapping = vec![
+ ("input_weights", packed_input_weights),
+ ("input_scales", input_scales),
+ ("input_biases", input_biases),
+ ("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);
+ }
+ },
}
}
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/mod.rs b/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
index 27fc8e53a..86654b28f 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
@@ -835,6 +835,10 @@ impl ForwardPassState {
input_weights,
..
} => input_weights.clone(),
+ EmbeddingsBuffers::MLXQuantizedUntied {
+ packed_input_weights,
+ ..
+ } => packed_input_weights.clone(),
}),
ArrayId::EmbeddingsOutputWeights => {
Some(match &shared.embeddings {
@@ -853,6 +857,10 @@ impl ForwardPassState {
packed_output_weights,
..
} => packed_output_weights.clone(),
+ EmbeddingsBuffers::MLXQuantizedUntied {
+ packed_output_weights,
+ ..
+ } => packed_output_weights.clone(),
})
},
ArrayId::EmbeddingsScales => Some(match &shared.embeddings {
@@ -864,6 +872,10 @@ impl ForwardPassState {
output_scales,
..
} => output_scales.clone(),
+ EmbeddingsBuffers::MLXQuantizedUntied {
+ output_scales,
+ ..
+ } => output_scales.clone(),
_ => panic!(
"Expected QuantizedTied or MLXSemiQuantizedUntied embeddings"
),
diff --git a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs
index cae917be8..c39215ca7 100644
--- a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs
+++ b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs
@@ -1,11 +1,9 @@
-#![allow(unexpected_cfgs)]
-
use metal::{
BufferRef, ComputeCommandEncoder, ComputeCommandEncoderRef,
MTLCompareFunction,
foreign_types::{ForeignType, ForeignTypeRef},
- objc::{msg_send, runtime::Object, sel, sel_impl},
};
+use objc2::{msg_send, runtime::AnyObject};
/// Low-level, unsafe conditional control of Metal encoders.
/// This is internal; users should prefer the safe `ComputeEncoderConditional::condition`.
@@ -43,24 +41,24 @@ impl ComputeEncoderRawConditional for ComputeCommandEncoder {
comparison: MTLCompareFunction,
reference_value: u32,
) {
- let obj = self.as_ptr() as *mut Object;
- let predicate_ptr = predicate.as_ptr() as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
+ let predicate_ptr = predicate.as_ptr() as *mut AnyObject;
let _: () = msg_send![
obj,
- encodeStartIf: predicate_ptr
- offset: offset
- comparison: comparison
+ encodeStartIf: predicate_ptr,
+ offset: offset,
+ comparison: comparison as u64,
referenceValue: reference_value
];
}
unsafe fn encode_start_else(&self) {
- let obj = self.as_ptr() as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
let _: () = msg_send![obj, encodeStartElse];
}
unsafe fn encode_end_if(&self) -> bool {
- let obj = self.as_ptr() as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
let result: bool = msg_send![obj, encodeEndIf];
result
}
@@ -74,24 +72,24 @@ impl ComputeEncoderRawConditional for ComputeCommandEncoderRef {
comparison: MTLCompareFunction,
reference_value: u32,
) {
- let obj = self as *const _ as *mut Object;
- let predicate_ptr = predicate.as_ptr() as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
+ let predicate_ptr = predicate.as_ptr() as *mut AnyObject;
let _: () = msg_send![
obj,
- encodeStartIf:predicate_ptr
- offset:offset
- comparison:comparison
- referenceValue:reference_value
+ encodeStartIf: predicate_ptr,
+ offset: offset,
+ comparison: comparison as u64,
+ referenceValue: reference_value
];
}
unsafe fn encode_start_else(&self) {
- let obj = self as *const _ as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
let _: () = msg_send![obj, encodeStartElse];
}
unsafe fn encode_end_if(&self) -> bool {
- let obj = self as *const _ as *mut Object;
+ let obj = self.as_ptr() as *mut AnyObject;
let result: bool = msg_send![obj, encodeEndIf];
result
}
diff --git a/crates/uzu/src/config/embedding.rs b/crates/uzu/src/config/embedding.rs
index f3277d2f7..490d76e37 100644
--- a/crates/uzu/src/config/embedding.rs
+++ b/crates/uzu/src/config/embedding.rs
@@ -40,6 +40,15 @@ pub enum EmbeddingConfig {
activation_quantization_mode: Option<QuantizationMode>,
activation_precision: ConfigDataType,
},
+ #[serde(rename = "MLXQuantizedUntiedEmbeddingConfig")]
+ MLXQuantizedUntied {
+ #[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)]
@@ -70,6 +79,10 @@ impl EmbeddingConfig {
common,
..
} => common,
+ EmbeddingConfig::MLXQuantizedUntied {
+ common,
+ ..
+ } => common,
EmbeddingConfig::MLXSemiQuantizedUntied {
common,
..
@@ -136,5 +149,32 @@ mod tests {
let deserialized: EmbeddingConfig = from_str(semi_config_str).unwrap();
assert_eq!(deserialized, semi_config);
+
+ let mlx_quant_untied_str = r#"
+ {
+ "type": "MLXQuantizedUntiedEmbeddingConfig",
+ "input_scale": null,
+ "logit_soft_cap": null,
+ "group_size": 128,
+ "embedding_quantization_mode": "uint4",
+ "activation_quantization_mode": null,
+ "activation_precision": "bfloat16"
+ }
+ "#;
+
+ let mlx_quant_untied = EmbeddingConfig::MLXQuantizedUntied {
+ 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(mlx_quant_untied_str).unwrap();
+ assert_eq!(deserialized, mlx_quant_untied);
}
}
diff --git a/scripts/tools/.gitignore b/scripts/tools/.gitignore
index 9cefeace5..1449f4d4b 100644
--- a/scripts/tools/.gitignore
+++ b/scripts/tools/.gitignore
@@ -35,3 +35,6 @@ sync.bb
# Profiler
memray-*.bin
memray-*.html
+
+# Local-only scripts
+validate_storage_local.py