A high-performance inference engine for AI models
generalize quantized embedding lookup
eugeneb274466d426c
diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding/mod.rs b/crates/uzu/src/backends/metal/encodable_block/embedding/mod.rsindex c9af38b13..836bb9c2c 100644--- a/crates/uzu/src/backends/metal/encodable_block/embedding/mod.rs+++ b/crates/uzu/src/backends/metal/encodable_block/embedding/mod.rs@@ -2,15 +2,17 @@mod error;mod full_precision_readout;-mod quantized_lookup;mod quantized_readout;pub use error::EmbeddingError;pub use full_precision_readout::FullPrecisionEmbeddingReadout;-pub use quantized_lookup::QuantizedEmbeddingLookup;pub use quantized_readout::QuantizedEmbeddingReadout;use super::super::Metal;-use crate::encodable_block::FullPrecisionEmbeddingLookup as GenericFullPrecisionEmbeddingLookup;+use crate::encodable_block::{+ FullPrecisionEmbeddingLookup as GenericFullPrecisionEmbeddingLookup,+ QuantizedEmbeddingLookup as GenericQuantizedEmbeddingLookup,+};pub type FullPrecisionEmbeddingLookup = GenericFullPrecisionEmbeddingLookup<Metal>;+pub type QuantizedEmbeddingLookup = GenericQuantizedEmbeddingLookup<Metal>;diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_lookup.rs b/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_lookup.rsdeleted file mode 100644index 023541b7c..000000000--- a/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_lookup.rs+++ /dev/null@@ -1,242 +0,0 @@-use super::{- super::{EncodableBlock, Metal},- EmbeddingError,-};-use crate::{- DataType,- backends::{- common::{Context, kernel::QuantizedEmbeddingLookupKernel},- metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLContext, MTLError,- ProtocolObject, Retained, kernel::dsl::QuantizedEmbeddingLookupMetalKernel,- },- },- config::QuantizationMode,- encodable_block::EncodingParameters,- forward_pass::state::{ArrayId, ForwardPassState},- parameters::ParameterTree,-};--pub struct QuantizedEmbeddingLookup {- kernel: QuantizedEmbeddingLookupMetalKernel,- weights_buffer: Retained<ProtocolObject<dyn MTLBuffer>>,- scales_buffer: Retained<ProtocolObject<dyn MTLBuffer>>,- biases_buffer: Retained<ProtocolObject<dyn MTLBuffer>>,- mode: QuantizationMode,- input_scale: f32,- vocab_size: u32,- model_dim: u32,- group_size: u32,-}--impl QuantizedEmbeddingLookup {- pub fn new_tied(- mtl_context: &MTLContext,- data_type: DataType,- vocab_size: usize,- model_dim: usize,- group_size: usize,- mode: QuantizationMode,- input_scale: f32,- parameter_tree: &ParameterTree<MTLContext>,- ) -> Result<Self, EmbeddingError> {- 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<MTLContext>,- ) -> Result<Self, EmbeddingError> {- 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<MTLContext>,- ) -> Result<Self, EmbeddingError> {- let packing_divisor = mode.packing_divisor();-- let kernel = QuantizedEmbeddingLookupMetalKernel::new(mtl_context, data_type.into())?;-- // Load weights [vocab_size, model_dim/packing_divisor] as storage_type- let weights = parameter_tree- .leaf(weights_name)- .map_err(|e| EmbeddingError::MetalError(MTLError::Generic(format!("Failed to load weights: {:?}", e))))?;-- if weights.data_type() != mode.storage_type() {- return Err(EmbeddingError::MetalError(MTLError::Generic(format!(- "Expected packed weights of type {:?}, got {:?}",- mode.storage_type(),- weights.data_type()- ))));- }-- // Load scales [vocab_size, num_groups]- let scales = parameter_tree- .leaf(scales_name)- .map_err(|e| EmbeddingError::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(EmbeddingError::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(EmbeddingError::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(EmbeddingError::UnsupportedDataType(scales.data_type()));- }-- // Load or create biases buffer [vocab_size, num_groups] (MLX key: "biases")- let biases_buffer: Retained<ProtocolObject<dyn MTLBuffer>> = match parameter_tree.leaf(biases_name) {- Ok(deq_biases) => {- if deq_biases.shape() != [vocab_size, num_groups] {- return Err(EmbeddingError::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(EmbeddingError::UnsupportedDataType(deq_biases.data_type()));- }- deq_biases.buffer().to_owned().into()- },- Err(_) => {- let elem_size: usize = match data_type {- DataType::F16 | DataType::BF16 => 2,- DataType::F32 => 4,- other => {- return Err(EmbeddingError::UnsupportedDataType(other));- },- };- let size_bytes = vocab_size * num_groups * elem_size;- let buf = mtl_context.create_buffer(size_bytes).expect("Failed to allocate buffer");- unsafe {- std::ptr::write_bytes(metal::MTLBuffer::contents(&*buf).as_ptr(), 0, size_bytes as usize);- }- buf- },- };-- let weights_buffer = weights.buffer().to_owned().into();- let scales_buffer = scales.buffer().to_owned().into();-- Ok(Self {- kernel,- weights_buffer,- scales_buffer,- biases_buffer,- mode,- input_scale,- vocab_size: vocab_size as u32,- model_dim: model_dim as u32,- group_size: group_size as u32,- })- }-}--impl EncodableBlock<Metal> for QuantizedEmbeddingLookup {- fn encode(- &self,- state: &mut ForwardPassState<Metal>,- parameters: &EncodingParameters<Metal>,- command_buffer: &Retained<ProtocolObject<dyn MTLCommandBuffer>>,- ) {- let encoder = command_buffer.new_compute_command_encoder().expect("Failed to create compute command encoder");- self.encode_with_shared_encoder(state, parameters, &encoder);- encoder.end_encoding();-- if parameters.wait_until_completed {- command_buffer.commit();- command_buffer.wait_until_completed();- }- }-- fn supports_shared_encoder(&self) -> bool {- true- }-- fn encode_with_shared_encoder(- &self,- state: &mut ForwardPassState<Metal>,- _parameters: &EncodingParameters<Metal>,- encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,- ) {- let arrays = state.arrays(&[ArrayId::TokenIds, ArrayId::Main]);- let batch_size = state.active_suffix_length();- let token_ids_array_mut = arrays[0].borrow_mut();- let output_array_mut = arrays[1].borrow_mut();-- let quant_mode = match self.mode {- QuantizationMode::UInt4 => 0,- QuantizationMode::Int8 => 1,- QuantizationMode::UInt8 => 2,- };- self.kernel.encode(- token_ids_array_mut.buffer(),- &self.weights_buffer,- &self.scales_buffer,- &self.biases_buffer,- output_array_mut.buffer(),- batch_size as u32,- self.vocab_size,- self.model_dim,- self.group_size,- self.input_scale,- quant_mode,- encoder,- )- }-}diff --git a/crates/uzu/src/encodable_block/mod.rs b/crates/uzu/src/encodable_block/mod.rsindex 0a0f6a2e4..e017b4f7a 100644--- a/crates/uzu/src/encodable_block/mod.rs+++ b/crates/uzu/src/encodable_block/mod.rs@@ -9,6 +9,7 @@ mod layer_norm;mod normalization;mod pooling;mod qk_norm;+mod quantized_embedding_lookup;mod rms_norm;mod rope;mod sampling;@@ -21,6 +22,7 @@ pub use layer_norm::{LayerNorm, LayerNormError};pub use normalization::{Normalization, NormalizationError};pub use pooling::Pooling;pub use qk_norm::{QKNorm, QKNormError};+pub use quantized_embedding_lookup::{QuantizedEmbeddingLookup, QuantizedEmbeddingLookupError};pub use rms_norm::{RMSNorm, RMSNormError};pub use rope::Rope;pub use sampling::Sampling;diff --git a/crates/uzu/src/encodable_block/quantized_embedding_lookup.rs b/crates/uzu/src/encodable_block/quantized_embedding_lookup.rsnew file mode 100644index 000000000..1a196e427--- /dev/null+++ b/crates/uzu/src/encodable_block/quantized_embedding_lookup.rs@@ -0,0 +1,272 @@+//! Quantized embedding lookup encodable.++use thiserror::Error;++use super::{EncodableBlock, EncodingParameters};+use crate::{+ DataType,+ backends::common::{+ Backend, Context, NativeBuffer,+ kernel::{Kernels, QuantizedEmbeddingLookupKernel},+ },+ config::QuantizationMode,+ forward_pass::state::{ArrayId, ForwardPassState},+ parameters::{ParameterLoaderError, ParameterTree},+};++#[derive(Debug, Error)]+pub enum QuantizedEmbeddingLookupError<B: Backend> {+ #[error("Backend error: {0}")]+ BackendError(#[source] B::Error),+ #[error("Parameter loading error: {0}")]+ ParameterError(ParameterLoaderError),+ #[error("Unsupported data type: {0:?}")]+ UnsupportedDataType(DataType),+ #[error("Expected packed weights of type {expected:?}, got {got:?}")]+ InvalidWeightsDataType {+ expected: DataType,+ got: DataType,+ },+ #[error(+ "Embedding lookup weights shape mismatch: got {got:?}, expected [{expected_vocab_size}, {expected_packed_dim}]"+ )]+ InvalidWeightsShape {+ got: Box<[usize]>,+ expected_vocab_size: usize,+ expected_packed_dim: usize,+ },+ #[error(+ "Embedding lookup scales shape mismatch: got {got:?}, expected [{expected_vocab_size}, {expected_num_groups}]"+ )]+ InvalidScalesShape {+ got: Box<[usize]>,+ expected_vocab_size: usize,+ expected_num_groups: usize,+ },+ #[error("Scales dtype mismatch: got {got:?}, expected {expected:?}")]+ InvalidScalesDataType {+ expected: DataType,+ got: DataType,+ },+ #[error(+ "Embedding lookup biases shape mismatch: got {got:?}, expected [{expected_vocab_size}, {expected_num_groups}]"+ )]+ InvalidBiasesShape {+ got: Box<[usize]>,+ expected_vocab_size: usize,+ expected_num_groups: usize,+ },+ #[error("Biases dtype mismatch: got {got:?}, expected {expected:?}")]+ InvalidBiasesDataType {+ expected: DataType,+ got: DataType,+ },+}++pub struct QuantizedEmbeddingLookup<B: Backend> {+ kernel: <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel,+ weights_buffer: B::NativeBuffer,+ scales_buffer: B::NativeBuffer,+ biases_buffer: B::NativeBuffer,+ mode: QuantizationMode,+ input_scale: f32,+ vocab_size: u32,+ model_dim: u32,+ group_size: u32,+}++impl<B: Backend> QuantizedEmbeddingLookup<B> {+ pub fn new_tied(+ context: &B::Context,+ data_type: DataType,+ vocab_size: usize,+ model_dim: usize,+ group_size: usize,+ mode: QuantizationMode,+ input_scale: f32,+ parameter_tree: &ParameterTree<B::Context>,+ ) -> Result<Self, QuantizedEmbeddingLookupError<B>> {+ Self::new_with_names(+ context,+ data_type,+ vocab_size,+ model_dim,+ group_size,+ mode,+ input_scale,+ "weights",+ "scales",+ "biases",+ parameter_tree,+ )+ }++ pub fn new_untied_input(+ context: &B::Context,+ data_type: DataType,+ vocab_size: usize,+ model_dim: usize,+ group_size: usize,+ mode: QuantizationMode,+ input_scale: f32,+ parameter_tree: &ParameterTree<B::Context>,+ ) -> Result<Self, QuantizedEmbeddingLookupError<B>> {+ Self::new_with_names(+ context,+ data_type,+ vocab_size,+ model_dim,+ group_size,+ mode,+ input_scale,+ "input_weights",+ "input_scales",+ "input_biases",+ parameter_tree,+ )+ }++ fn new_with_names(+ context: &B::Context,+ 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<B::Context>,+ ) -> Result<Self, QuantizedEmbeddingLookupError<B>> {+ let packing_divisor = mode.packing_divisor();++ let kernel = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(context, data_type)+ .map_err(QuantizedEmbeddingLookupError::BackendError)?;++ let weights = parameter_tree.leaf(weights_name).map_err(QuantizedEmbeddingLookupError::ParameterError)?;++ if weights.data_type() != mode.storage_type() {+ return Err(QuantizedEmbeddingLookupError::InvalidWeightsDataType {+ expected: mode.storage_type(),+ got: weights.data_type(),+ });+ }++ let scales = parameter_tree.leaf(scales_name).map_err(QuantizedEmbeddingLookupError::ParameterError)?;++ let num_groups = (model_dim + group_size - 1) / group_size;+ if weights.shape() != [vocab_size, model_dim / packing_divisor] {+ return Err(QuantizedEmbeddingLookupError::InvalidWeightsShape {+ got: weights.shape().to_vec().into_boxed_slice(),+ expected_vocab_size: vocab_size,+ expected_packed_dim: model_dim / packing_divisor,+ });+ }++ if scales.shape() != [vocab_size, num_groups] {+ return Err(QuantizedEmbeddingLookupError::InvalidScalesShape {+ got: scales.shape().to_vec().into_boxed_slice(),+ expected_vocab_size: vocab_size,+ expected_num_groups: num_groups,+ });+ }++ if scales.data_type() != data_type {+ return Err(QuantizedEmbeddingLookupError::InvalidScalesDataType {+ expected: data_type,+ got: scales.data_type(),+ });+ }++ let biases_buffer = match parameter_tree.leaf(biases_name) {+ Ok(biases) => {+ if biases.shape() != [vocab_size, num_groups] {+ return Err(QuantizedEmbeddingLookupError::InvalidBiasesShape {+ got: biases.shape().to_vec().into_boxed_slice(),+ expected_vocab_size: vocab_size,+ expected_num_groups: num_groups,+ });+ }++ if biases.data_type() != data_type {+ return Err(QuantizedEmbeddingLookupError::InvalidBiasesDataType {+ expected: data_type,+ got: biases.data_type(),+ });+ }++ biases.buffer().clone()+ },+ Err(_) => {+ let element_size = match data_type {+ DataType::F16 | DataType::BF16 => 2,+ DataType::F32 => 4,+ other => {+ return Err(QuantizedEmbeddingLookupError::UnsupportedDataType(other));+ },+ };++ let size_bytes = vocab_size * num_groups * element_size;+ let buffer = context.create_buffer(size_bytes).map_err(QuantizedEmbeddingLookupError::BackendError)?;++ unsafe {+ std::ptr::write_bytes(buffer.cpu_ptr().as_ptr().cast::<u8>(), 0, size_bytes);+ }++ buffer+ },+ };++ Ok(Self {+ kernel,+ weights_buffer: weights.buffer().clone(),+ scales_buffer: scales.buffer().clone(),+ biases_buffer,+ mode,+ input_scale,+ vocab_size: vocab_size as u32,+ model_dim: model_dim as u32,+ group_size: group_size as u32,+ })+ }+}++impl<B: Backend> EncodableBlock<B> for QuantizedEmbeddingLookup<B> {+ fn supports_shared_encoder(&self) -> bool {+ true+ }++ fn encode_with_shared_encoder(+ &self,+ state: &mut ForwardPassState<B>,+ _parameters: &EncodingParameters<B>,+ encoder: &B::ComputeEncoder,+ ) {+ let arrays = state.arrays(&[ArrayId::TokenIds, ArrayId::Main]);+ let batch_size = state.active_suffix_length();+ let token_ids_array = arrays[0].borrow_mut();+ let output_array = arrays[1].borrow_mut();++ let quant_mode = match self.mode {+ QuantizationMode::UInt4 => 0,+ QuantizationMode::Int8 => 1,+ QuantizationMode::UInt8 => 2,+ };++ self.kernel.encode(+ token_ids_array.buffer(),+ &self.weights_buffer,+ &self.scales_buffer,+ &self.biases_buffer,+ output_array.buffer(),+ batch_size as u32,+ self.vocab_size,+ self.model_dim,+ self.group_size,+ self.input_scale,+ quant_mode,+ encoder,+ );+ }+}