A high-performance inference engine for AI models
Enable quantized PLE and unify weight-matrix loading (#693)
CCYeh9bc4cbdadd57
diff --git a/crates/backend-uzu/src/encodable_block/embedding.rs b/crates/backend-uzu/src/encodable_block/embedding.rsindex ef35118e1..9be38f3e5 100644--- a/crates/backend-uzu/src/encodable_block/embedding.rs+++ b/crates/backend-uzu/src/encodable_block/embedding.rs@@ -5,24 +5,24 @@ use crate::{array::size_for_shape,backends::common::{Allocation, Backend, Encoder, Kernels,- gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},+ gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,kernel::{- ActivationTransform, FullPrecisionEmbeddingLookupKernel, LogitSoftCapKernel,- QuantizedEmbeddingLookupKernel,- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ ActivationTransform, LogitSoftCapKernel,+ matmul::{MatmulA, MatmulArguments, MatmulDOps, MatmulKernel},},},config::{embedding::AnyEmbeddingConfig,weight_matrix::{AnyWeightMatrixSpec, Layout,- full_precision_spec::FullPrecisionSpec,hybrid_spec::{HybridSpec, IncoherenceProcessingMode},- int_spec::IntSpec,- mlx_spec::MLXSpec,},},data_type::DataType,+ encodable_block::{+ embedding_table::{EmbeddingTable, EmbeddingTableError},+ weight_matrix::{WeightMatrix, WeightMatrixError},+ },parameters::{ParameterLoaderError, ParameterTree},};@@ -34,60 +34,16 @@ pub enum EmbeddingError<B: Backend> {ParameterError(#[from] ParameterLoaderError<B>),#[error("Unsupported configuration: {0}")]UnsupportedConfiguration(String),+ #[error("Embedding table error: {0}")]+ EmbeddingTable(#[from] EmbeddingTableError<B>),+ #[error("Weight matrix error: {0}")]+ WeightMatrix(#[from] WeightMatrixError<B>),}-struct ReadoutQuantConfig {- method: QuantizationMethod,- mode: QuantizationMode,- group_size: u32,-}--enum TiedEmbeddingType<B: Backend> {- FullPrecision {- weights: Allocation<B>,- lookup: <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel,- readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- },- Quantized {- weights: Allocation<B>,- scales: Allocation<B>,- zero_points_or_biases: Option<Allocation<B>>,- quantization_method: QuantizationMethod,- output_hadamard_factors: Option<Allocation<B>>,- lookup: <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel,- readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- readout_config: ReadoutQuantConfig,- },-}--enum UntiedEmbeddingLookupType<B: Backend> {- FullPrecision {- weights: Allocation<B>,- lookup: <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel,- },- Quantized {- weights: Allocation<B>,- scales: Allocation<B>,- zero_points_or_biases: Option<Allocation<B>>,- quantization_method: QuantizationMethod,- output_hadamard_factors: Option<Allocation<B>>,- lookup: <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel,- },-}--enum UntiedEmbeddingReadoutType<B: Backend> {- FullPrecision {- weights: Allocation<B>,- readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- },- Quantized {- weights: Allocation<B>,- scales: Allocation<B>,- zero_points_or_biases: Option<Allocation<B>>,- readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- readout_config: ReadoutQuantConfig,- input_hadamard: Option<InputHadamard<B>>,- },+struct UntiedReadout<B: Backend> {+ matrix: WeightMatrix<B>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,+ input_hadamard: Option<InputHadamard<B>>,}struct InputHadamard<B: Backend> {@@ -97,11 +53,12 @@ struct InputHadamard<B: Backend> {enum EmbeddingTying<B: Backend> {Tied {- ty: TiedEmbeddingType<B>,+ table: EmbeddingTable<B>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,},Untied {- input_ty: UntiedEmbeddingLookupType<B>,- output_ty: UntiedEmbeddingReadoutType<B>,+ input_table: EmbeddingTable<B>,+ output: UntiedReadout<B>,},}@@ -132,6 +89,31 @@ impl<B: Backend> Embedding<B> {self.model_dim as usize}+ fn readout_input_hadamard(&self) -> Option<&InputHadamard<B>> {+ match &self.tying {+ EmbeddingTying::Untied {+ output,+ ..+ } => output.input_hadamard.as_ref(),+ EmbeddingTying::Tied {+ ..+ } => None,+ }+ }++ fn readout_operands(&self) -> (&WeightMatrix<B>, &Mutex<<B::Kernels as Kernels>::MatmulKernel>) {+ match &self.tying {+ EmbeddingTying::Tied {+ table,+ readout,+ } => (table.matrix(), readout),+ EmbeddingTying::Untied {+ output,+ ..+ } => (&output.matrix, &output.readout),+ }+ }+pub fn new(context: &B::Context,vocab_size: u32,@@ -145,73 +127,24 @@ impl<B: Backend> Embedding<B> {let embedding_tree = parameter_tree.subtree("embedding")?;let embedding_spec = embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- let (ty, readout_input_hadamard_factors) = match embedding_spec {- AnyWeightMatrixSpec::FullPrecisionSpec(FullPrecisionSpec {- layout: Layout::InputOutput,- ..- }) => {- let weights = embedding_tree- .leaf("weights")?- .validate(&[vocab_size as usize, model_dim as usize], data_type)?- .read_allocation()?;-- let lookup =- <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)- .map_err(EmbeddingError::BackendError)?;- let readout_kernel =- <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)- .map_err(EmbeddingError::BackendError)?;- let readout = Mutex::new(readout_kernel);-- (- TiedEmbeddingType::FullPrecision {- weights,- lookup,- readout,- },- None,- )- },- spec @ (AnyWeightMatrixSpec::MLXSpec(_) | AnyWeightMatrixSpec::IntSpec(_)) => {- let (embedding_quantization_mode, group_size, quantization_method) =- input_quantization_from_spec(spec)?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(+ let (tying, readout_input_hadamard_factors) = match embedding_spec {+ spec @ (AnyWeightMatrixSpec::FullPrecisionSpec(_)+ | AnyWeightMatrixSpec::MLXSpec(_)+ | AnyWeightMatrixSpec::IntSpec(_)) => {+ let table = EmbeddingTable::load_with_spec(+ context,&embedding_tree,vocab_size as usize,model_dim as usize,data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;-- let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(- context,- data_type,- group_size as u32,- embedding_quantization_mode,- quantization_method,- false,- )- .map_err(EmbeddingError::BackendError)?;- let (readout, readout_config) = quantized_readout(- context,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,+ spec,+ None,)?;(- TiedEmbeddingType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,- output_hadamard_factors: None,- lookup,- readout,- readout_config,+ EmbeddingTying::Tied {+ table,+ readout: readout_kernel(context, data_type)?,},None,)@@ -223,19 +156,6 @@ impl<B: Backend> Embedding<B> {incoherence_processing_mode: IncoherenceProcessingMode::Output,..}) => {- let (embedding_quantization_mode, group_size, quantization_method) =- input_quantization_from_spec(*quantization_spec)?;- let quantized_tree = embedding_tree.subtree("quantized")?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(- &quantized_tree,- vocab_size as usize,- model_dim as usize,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;-let incoherence_signs_tree = embedding_tree.subtree("incoherence_signs")?;let output_hadamard_factors = Some(incoherence_signs_tree@@ -249,33 +169,20 @@ impl<B: Backend> Embedding<B> {.validate(&[model_dim as usize], DataType::I32)?.read_allocation()?,);- let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(- context,- data_type,- group_size as u32,- embedding_quantization_mode,- quantization_method,- true,- )- .map_err(EmbeddingError::BackendError)?;- let (readout, readout_config) = quantized_readout(++ let table = EmbeddingTable::load_with_spec(context,+ &embedding_tree.subtree("quantized")?,+ vocab_size as usize,+ model_dim as usize,data_type,- embedding_quantization_mode,- quantization_method,- group_size,+ *quantization_spec,+ output_hadamard_factors,)?;-(- TiedEmbeddingType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,- output_hadamard_factors,- lookup,- readout,- readout_config,+ EmbeddingTying::Tied {+ table,+ readout: readout_kernel(context, data_type)?,},readout_input_hadamard_factors,)@@ -283,68 +190,13 @@ impl<B: Backend> Embedding<B> {spec => return Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),};- (- EmbeddingTying::Tied {- ty,- },- readout_input_hadamard_factors,- )+ (tying, readout_input_hadamard_factors)},AnyEmbeddingConfig::UntiedEmbeddingConfig(_) => {let input_embedding_tree = parameter_tree.subtree("input_embedding")?;let input_embedding_spec = input_embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- let input_ty = match input_embedding_spec {- AnyWeightMatrixSpec::FullPrecisionSpec(FullPrecisionSpec {- layout: Layout::InputOutput,- ..- }) => {- let weights = input_embedding_tree- .leaf("weights")?- .validate(&[vocab_size as usize, model_dim as usize], data_type)?- .read_allocation()?;-- let lookup =- <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)- .map_err(EmbeddingError::BackendError)?;-- UntiedEmbeddingLookupType::FullPrecision {- weights,- lookup,- }- },- spec @ (AnyWeightMatrixSpec::MLXSpec(_) | AnyWeightMatrixSpec::IntSpec(_)) => {- let (embedding_quantization_mode, group_size, quantization_method) =- input_quantization_from_spec(spec)?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(- &input_embedding_tree,- vocab_size as usize,- model_dim as usize,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;-- let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(- context,- data_type,- group_size as u32,- embedding_quantization_mode,- quantization_method,- false,- )- .map_err(EmbeddingError::BackendError)?;-- UntiedEmbeddingLookupType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,- output_hadamard_factors: None,- lookup,- }- },+ let input_table = match input_embedding_spec {AnyWeightMatrixSpec::HybridSpec(HybridSpec {quantization_spec,adapter_spec: None,@@ -352,99 +204,38 @@ impl<B: Backend> Embedding<B> {incoherence_processing_mode: IncoherenceProcessingMode::Output,..}) => {- let (embedding_quantization_mode, group_size, quantization_method) =- input_quantization_from_spec(*quantization_spec)?;- let quantized_tree = input_embedding_tree.subtree("quantized")?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(- &quantized_tree,- vocab_size as usize,- model_dim as usize,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;-- let incoherence_signs_tree = input_embedding_tree.subtree("incoherence_signs")?;let output_hadamard_factors = Some(- incoherence_signs_tree+ input_embedding_tree+ .subtree("incoherence_signs")?.leaf("output_signs")?.validate(&[model_dim as usize], DataType::I32)?.read_allocation()?,);- let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(+ EmbeddingTable::load_with_spec(context,+ &input_embedding_tree.subtree("quantized")?,+ vocab_size as usize,+ model_dim as usize,data_type,- group_size as u32,- embedding_quantization_mode,- quantization_method,- true,- )- .map_err(EmbeddingError::BackendError)?;-- UntiedEmbeddingLookupType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,+ *quantization_spec,output_hadamard_factors,- lookup,- }+ )?},- spec => return Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),+ spec => EmbeddingTable::load_with_spec(+ context,+ &input_embedding_tree,+ vocab_size as usize,+ model_dim as usize,+ data_type,+ spec,+ None,+ )?,};let output_embedding_tree = parameter_tree.subtree("output_embedding")?;let output_embedding_spec = output_embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- let output_ty = match output_embedding_spec {- AnyWeightMatrixSpec::FullPrecisionSpec(FullPrecisionSpec {- layout: Layout::OutputInput,- ..- }) => {- let weights = output_embedding_tree- .leaf("weights")?- .validate(&[vocab_size as usize, model_dim as usize], data_type)?- .read_allocation()?;- let readout_kernel =- <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)- .map_err(EmbeddingError::BackendError)?;- let readout = Mutex::new(readout_kernel);-- UntiedEmbeddingReadoutType::FullPrecision {- weights,- readout,- }- },- spec @ (AnyWeightMatrixSpec::MLXSpec(_) | AnyWeightMatrixSpec::IntSpec(_)) => {- let (embedding_quantization_mode, group_size, quantization_method) =- output_quantization_from_spec(spec)?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(- &output_embedding_tree,- vocab_size as usize,- model_dim as usize,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;- let (readout, readout_config) = quantized_readout(- context,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;-- UntiedEmbeddingReadoutType::Quantized {- weights,- scales,- zero_points_or_biases,- readout,- readout_config,- input_hadamard: None,- }- },+ let output = match output_embedding_spec {AnyWeightMatrixSpec::HybridSpec(HybridSpec {quantization_spec,adapter_spec: None,@@ -452,57 +243,56 @@ impl<B: Backend> Embedding<B> {incoherence_processing_mode: IncoherenceProcessingMode::Input,..}) => {- let (embedding_quantization_mode, group_size, quantization_method) =- output_quantization_from_spec(*quantization_spec)?;- let quantized_tree = output_embedding_tree.subtree("quantized")?;- let (weights, scales, zero_points_or_biases) = load_quantized_embedding_parts(- &quantized_tree,+ let matrix = WeightMatrix::load(+ &output_embedding_tree.subtree("quantized")?,+ *quantization_spec,+ Layout::OutputInput,vocab_size as usize,model_dim as usize,data_type,- embedding_quantization_mode,- quantization_method,- group_size,- )?;- let (readout, readout_config) = quantized_readout(- context,- data_type,- embedding_quantization_mode,- quantization_method,- group_size,)?;// Input-side incoherence is applied privately to the readout// input: the shared hidden state must stay untransformed// (e.g. for the speculator).- let incoherence_signs_tree = output_embedding_tree.subtree("incoherence_signs")?;- let factors = incoherence_signs_tree+ let factors = output_embedding_tree+ .subtree("incoherence_signs")?.leaf("input_signs")?.validate(&[model_dim as usize], DataType::I32)?.read_allocation()?;let kernel = ActivationTransform::input_rht(context, data_type, false).map_err(EmbeddingError::BackendError)?;- let input_hadamard = Some(InputHadamard {- factors,- kernel,- });- UntiedEmbeddingReadoutType::Quantized {- weights,- scales,- zero_points_or_biases,- readout,- readout_config,- input_hadamard,+ UntiedReadout {+ matrix,+ readout: readout_kernel(context, data_type)?,+ input_hadamard: Some(InputHadamard {+ factors,+ kernel,+ }),+ }+ },+ spec => {+ let matrix = WeightMatrix::load(+ &output_embedding_tree,+ spec,+ Layout::OutputInput,+ vocab_size as usize,+ model_dim as usize,+ data_type,+ )?;+ UntiedReadout {+ matrix,+ readout: readout_kernel(context, data_type)?,+ input_hadamard: None,}},- spec => return Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),};(EmbeddingTying::Untied {- input_ty,- output_ty,+ input_table,+ output,},None,)@@ -547,78 +337,17 @@ impl<B: Backend> Embedding<B> {.map_err(EmbeddingError::BackendError)?;let batch_dim = batch_dim as u32;- match &self.tying {- EmbeddingTying::Tied {- ty:- TiedEmbeddingType::FullPrecision {- weights,- lookup,- readout: _,- },- }- | EmbeddingTying::Untied {- input_ty:- UntiedEmbeddingLookupType::FullPrecision {- weights,- lookup,- },- output_ty: _,- } => lookup.encode(- token_ids,- weights,- &mut output,- batch_dim,- self.vocab_size,- self.model_dim,- self.input_scale,- encoder,- ),+ let table = match &self.tying {EmbeddingTying::Tied {- ty:- TiedEmbeddingType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,- output_hadamard_factors,- lookup,- readout: _,- readout_config: _,- },- }- | EmbeddingTying::Untied {- input_ty:- UntiedEmbeddingLookupType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method,- output_hadamard_factors,- lookup,- },- output_ty: _,- } => {- let (zero_points, biases) = match quantization_method {- QuantizationMethod::ScaleBias => (None, zero_points_or_biases.as_ref()),- QuantizationMethod::ScaleZeroPoint => (zero_points_or_biases.as_ref(), None),- QuantizationMethod::ScaleSymmetric => (None, None),- };- lookup.encode(- token_ids,- weights,- scales,- zero_points,- biases,- &mut output,- output_hadamard_factors.as_ref(),- batch_dim,- self.vocab_size,- self.model_dim,- self.input_scale,- encoder,- );- },+ table,+ ..+ } => table,+ EmbeddingTying::Untied {+ input_table,+ ..+ } => input_table,};+ table.encode_lookup(token_ids, &mut output, batch_dim, self.input_scale, encoder);encoder.pop_debug_group();@@ -636,140 +365,56 @@ impl<B: Backend> Embedding<B> {assert!(batch_dim > 0, "Embedding readout requires at least one row");let native_output = output_data_type == self.data_type;- let input_hadamard = match &self.tying {- EmbeddingTying::Untied {- output_ty:- UntiedEmbeddingReadoutType::Quantized {- input_hadamard,- ..- },- ..- } => input_hadamard.as_ref(),- _ => None,- };+ let input_hadamard = self.readout_input_hadamard();let mut output_allocation = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.vocab_size as usize], output_data_type)).map_err(EmbeddingError::BackendError)?;- match &self.tying {- EmbeddingTying::Tied {- ty:- TiedEmbeddingType::FullPrecision {- weights,- lookup: _,- readout,- },- }- | EmbeddingTying::Untied {- input_ty: _,- output_ty:- UntiedEmbeddingReadoutType::FullPrecision {- weights,- readout,- },- } => {- let arguments = MatmulArguments {- a: MatmulA::FullPrecision {- values: input_allocation,- offset: 0,- },- b: MatmulB::FullPrecision {- b: weights,- },- b_leading_dimension: None,- b_transpose: true,- d: &mut output_allocation,- d_transform: MatmulDOps::none(),- gather_indices: None,- m: batch_dim as u32,- n: self.vocab_size,- k: self.model_dim,- };- if native_output {- readout.lock().encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;- } else {- let mut widened = <B::Kernels as Kernels>::MatmulKernel::new(- encoder.context(),- self.data_type,- self.data_type,- output_data_type,- )- .map_err(EmbeddingError::BackendError)?;- widened.encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;- }+ let (matrix, readout) = self.readout_operands();+ let mut rht_input: Option<Allocation<B>> = None;+ let a = match input_hadamard {+ Some(input_hadamard) => {+ let mut transformed =+ encoder.allocate_scratch(input_allocation.size()).map_err(EmbeddingError::BackendError)?;+ input_hadamard.kernel.encode_fp(+ input_allocation,+ &mut transformed,+ &input_hadamard.factors,+ batch_dim as u32,+ self.model_dim,+ encoder,+ );+ rht_input.insert(transformed)},- EmbeddingTying::Tied {- ty:- TiedEmbeddingType::Quantized {- weights,- scales,- zero_points_or_biases,- quantization_method: _,- output_hadamard_factors: _,- lookup: _,- readout,- readout_config,- },- }- | EmbeddingTying::Untied {- input_ty: _,- output_ty:- UntiedEmbeddingReadoutType::Quantized {- weights,- scales,- zero_points_or_biases,- readout,- readout_config,- ..- },- } => {- let b = quantized_matmul_b(weights, scales, zero_points_or_biases.as_ref(), readout_config);- let mut rht_input: Option<Allocation<B>> = None;- let a = match input_hadamard {- Some(input_hadamard) => {- let mut transformed =- encoder.allocate_scratch(input_allocation.size()).map_err(EmbeddingError::BackendError)?;- input_hadamard.kernel.encode_fp(- input_allocation,- &mut transformed,- &input_hadamard.factors,- batch_dim as u32,- self.model_dim,- encoder,- );- rht_input.insert(transformed)- },- None => input_allocation,- };- let arguments = MatmulArguments {- a: MatmulA::FullPrecision {- values: a,- offset: 0,- },- b,- b_leading_dimension: None,- b_transpose: true,- d: &mut output_allocation,- d_transform: MatmulDOps::none(),- gather_indices: None,- m: batch_dim as u32,- n: self.vocab_size,- k: self.model_dim,- };- if native_output {- readout.lock().encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;- } else {- let mut widened = <B::Kernels as Kernels>::MatmulKernel::new(- encoder.context(),- self.data_type,- self.data_type,- output_data_type,- )- .map_err(EmbeddingError::BackendError)?;- widened.encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;- }+ None => input_allocation,+ };+ let arguments = MatmulArguments {+ a: MatmulA::FullPrecision {+ values: a,+ offset: 0,},+ b: matrix.matmul_b(),+ b_leading_dimension: None,+ b_transpose: true,+ d: &mut output_allocation,+ d_transform: MatmulDOps::none(),+ gather_indices: None,+ m: batch_dim as u32,+ n: self.vocab_size,+ k: self.model_dim,};+ if native_output {+ readout.lock().encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;+ } else {+ let mut widened = <B::Kernels as Kernels>::MatmulKernel::new(+ encoder.context(),+ self.data_type,+ self.data_type,+ output_data_type,+ )+ .map_err(EmbeddingError::BackendError)?;+ widened.encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;+ }if let Some(logit_soft_cap) = &self.logit_soft_cap {let length = (batch_dim * self.vocab_size as usize) as u32;@@ -800,63 +445,9 @@ impl<B: Backend> Embedding<B> {encoder.push_debug_group("embedding readout (sparse)");assert!(rows > 0 && ids_per_row > 0);- let (b, readout, input_hadamard) = match &self.tying {- EmbeddingTying::Tied {- ty:- TiedEmbeddingType::FullPrecision {- weights,- readout,- ..- },- } => (- MatmulB::FullPrecision {- b: weights,- },- readout,- None,- ),- EmbeddingTying::Untied {- output_ty:- UntiedEmbeddingReadoutType::FullPrecision {- weights,- readout,- },- ..- } => (- MatmulB::FullPrecision {- b: weights,- },- readout,- None,- ),- EmbeddingTying::Tied {- ty:- TiedEmbeddingType::Quantized {- weights,- scales,- zero_points_or_biases,- readout,- readout_config,- ..- },- } => (quantized_matmul_b(weights, scales, zero_points_or_biases.as_ref(), readout_config), readout, None),- EmbeddingTying::Untied {- output_ty:- UntiedEmbeddingReadoutType::Quantized {- weights,- scales,- zero_points_or_biases,- readout,- readout_config,- input_hadamard,- },- ..- } => (- quantized_matmul_b(weights, scales, zero_points_or_biases.as_ref(), readout_config),- readout,- input_hadamard.as_ref(),- ),- };+ let input_hadamard = self.readout_input_hadamard();+ let (matrix, readout) = self.readout_operands();+ let b = matrix.matmul_b();let mut output = encoder.allocate_scratch(size_for_shape(&[rows, ids_per_row], self.data_type))@@ -911,163 +502,11 @@ impl<B: Backend> Embedding<B> {}}-fn quantized_matmul_b<'a, B: Backend>(- weights: &'a Allocation<B>,- scales: &'a Allocation<B>,- zero_points_or_biases: Option<&'a Allocation<B>>,- readout_config: &ReadoutQuantConfig,-) -> MatmulB<'a, B> {- match readout_config.method {- QuantizationMethod::ScaleBias => MatmulB::ScaleBiasDequant {- b: weights,- scales,- biases: zero_points_or_biases.expect("ScaleBias quantization requires biases"),- mode: readout_config.mode,- group_size: readout_config.group_size,- signed_codes: false,- },- QuantizationMethod::ScaleZeroPoint => MatmulB::ScaleZeroPointDequant {- b: weights,- scales,- zero_points: zero_points_or_biases.expect("ScaleZeroPoint quantization requires zero_points"),- mode: readout_config.mode,- group_size: readout_config.group_size,- signed_codes: false,- },- QuantizationMethod::ScaleSymmetric => MatmulB::ScaleSymmetricDequant {- b: weights,- scales,- mode: readout_config.mode,- group_size: readout_config.group_size,- signed_codes: false,- },- }-}--fn input_quantization_from_spec<B: Backend>(- spec: AnyWeightMatrixSpec-) -> Result<(QuantizationMode, usize, QuantizationMethod), EmbeddingError<B>> {- match spec {- AnyWeightMatrixSpec::MLXSpec(MLXSpec {- bits,- group_size,- layout: Layout::InputOutput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleBias),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: false,- layout: Layout::InputOutput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleZeroPoint),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: true,- layout: Layout::InputOutput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleSymmetric),- spec => Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),- }-}--fn output_quantization_from_spec<B: Backend>(- spec: AnyWeightMatrixSpec-) -> Result<(QuantizationMode, usize, QuantizationMethod), EmbeddingError<B>> {- match spec {- AnyWeightMatrixSpec::MLXSpec(MLXSpec {- bits,- group_size,- layout: Layout::OutputInput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleBias),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: false,- layout: Layout::OutputInput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleZeroPoint),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: true,- layout: Layout::OutputInput,- ..- }) => quantization_mode(bits, group_size, QuantizationMethod::ScaleSymmetric),- spec => Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),- }-}--fn quantization_mode<B: Backend>(- bits: u32,- group_size: usize,- method: QuantizationMethod,-) -> Result<(QuantizationMode, usize, QuantizationMethod), EmbeddingError<B>> {- let mode = match bits {- 4 => QuantizationMode::U4,- 8 => QuantizationMode::U8,- _ => {- return Err(EmbeddingError::UnsupportedConfiguration(format!(- "{method:?} bits={bits}, group_size={group_size}"- )));- },- };- Ok((mode, group_size, method))-}--fn load_quantized_embedding_parts<B: Backend>(- tree: &ParameterTree<B>,- vocab_size: usize,- model_dim: usize,- data_type: DataType,- quantization_mode: QuantizationMode,- quantization_method: QuantizationMethod,- group_size: usize,-) -> Result<(Allocation<B>, Allocation<B>, Option<Allocation<B>>), EmbeddingError<B>> {- let packing_divisor = quantization_mode.packing_divisor();- let storage_data_type = quantization_mode.storage_type();- let num_groups = model_dim.div_ceil(group_size);-- let weights = tree- .leaf("weights")?- .validate(&[vocab_size, model_dim / packing_divisor], storage_data_type)?- .read_allocation()?;- let scales = tree.leaf("scales")?.validate(&[vocab_size, num_groups], data_type)?.read_allocation()?;- let zero_points_or_biases = match quantization_method {- QuantizationMethod::ScaleBias => {- Some(tree.leaf("biases")?.validate(&[vocab_size, num_groups], data_type)?.read_allocation()?)- },- QuantizationMethod::ScaleZeroPoint => {- let expected_zero_points_entries = num_groups.div_ceil(packing_divisor);- Some(- tree.leaf("zero_points")?- .validate(&[vocab_size, expected_zero_points_entries], storage_data_type)?- .read_allocation()?,- )- },- QuantizationMethod::ScaleSymmetric => None,- };-- Ok((weights, scales, zero_points_or_biases))-}--fn quantized_readout<B: Backend>(+fn readout_kernel<B: Backend>(context: &B::Context,data_type: DataType,- mode: QuantizationMode,- method: QuantizationMethod,- group_size: usize,-) -> Result<(Mutex<<B::Kernels as Kernels>::MatmulKernel>, ReadoutQuantConfig), EmbeddingError<B>> {- let readout = <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)+) -> Result<Mutex<<B::Kernels as Kernels>::MatmulKernel>, EmbeddingError<B>> {+ let kernel = <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type).map_err(EmbeddingError::BackendError)?;- Ok((- Mutex::new(readout),- ReadoutQuantConfig {- method,- mode,- group_size: group_size as u32,- },- ))+ Ok(Mutex::new(kernel))}diff --git a/crates/backend-uzu/src/encodable_block/embedding_table.rs b/crates/backend-uzu/src/encodable_block/embedding_table.rsnew file mode 100644index 000000000..3df7e8e73--- /dev/null+++ b/crates/backend-uzu/src/encodable_block/embedding_table.rs@@ -0,0 +1,134 @@+use thiserror::Error;++use crate::{+ backends::common::{+ Allocation, Backend, Encoder, Kernels,+ kernel::{FullPrecisionEmbeddingLookupKernel, QuantizedEmbeddingLookupKernel},+ },+ config::weight_matrix::{AnyWeightMatrixSpec, Layout},+ data_type::DataType,+ encodable_block::weight_matrix::{WeightMatrix, WeightMatrixError},+ parameters::{ParameterLoaderError, ParameterTree},+};++#[derive(Debug, Error)]+pub enum EmbeddingTableError<B: Backend> {+ #[error("Backend error: {0}")]+ BackendError(#[source] B::Error),+ #[error("Parameter loading error: {0}")]+ ParameterError(#[from] ParameterLoaderError<B>),+ #[error("Weight matrix error: {0}")]+ WeightMatrix(#[from] WeightMatrixError<B>),+ #[error("Unsupported embedding table configuration: {0}")]+ UnsupportedConfiguration(String),+}++enum LookupKernel<B: Backend> {+ FullPrecision(<B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel),+ Quantized(<B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel),+}++pub struct EmbeddingTable<B: Backend> {+ matrix: WeightMatrix<B>,+ lookup: LookupKernel<B>,+ output_hadamard_factors: Option<Allocation<B>>,+ vocab_size: u32,+ embedding_dim: u32,+}++impl<B: Backend> EmbeddingTable<B> {+ pub fn load(+ context: &B::Context,+ tree: &ParameterTree<B>,+ vocab_size: usize,+ embedding_dim: usize,+ data_type: DataType,+ ) -> Result<Self, EmbeddingTableError<B>> {+ let spec = tree.metadata::<AnyWeightMatrixSpec>("spec")?;+ Self::load_with_spec(context, tree, vocab_size, embedding_dim, data_type, spec, None)+ }++ pub fn load_with_spec(+ context: &B::Context,+ tree: &ParameterTree<B>,+ vocab_size: usize,+ embedding_dim: usize,+ data_type: DataType,+ spec: AnyWeightMatrixSpec,+ output_hadamard_factors: Option<Allocation<B>>,+ ) -> Result<Self, EmbeddingTableError<B>> {+ let matrix = WeightMatrix::load(tree, spec, Layout::InputOutput, embedding_dim, vocab_size, data_type)?;+ if output_hadamard_factors.is_some() && matrix.quantization().is_none() {+ return Err(EmbeddingTableError::UnsupportedConfiguration(+ "output-hadamard factors require a quantized table".into(),+ ));+ }++ let lookup = match matrix.quantization() {+ None => LookupKernel::FullPrecision(+ <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)+ .map_err(EmbeddingTableError::BackendError)?,+ ),+ Some(info) => LookupKernel::Quantized(+ <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(+ context,+ data_type,+ info.group_size,+ info.mode,+ info.method,+ output_hadamard_factors.is_some(),+ )+ .map_err(EmbeddingTableError::BackendError)?,+ ),+ };++ Ok(Self {+ matrix,+ lookup,+ output_hadamard_factors,+ vocab_size: vocab_size as u32,+ embedding_dim: embedding_dim as u32,+ })+ }++ pub fn matrix(&self) -> &WeightMatrix<B> {+ &self.matrix+ }++ /// Gathers one row per token id into `output`, scaling by `scale`.+ pub fn encode_lookup(+ &self,+ token_ids: &Allocation<B>,+ output: &mut Allocation<B>,+ batch_dim: u32,+ scale: f32,+ encoder: &mut Encoder<B>,+ ) {+ match &self.lookup {+ LookupKernel::FullPrecision(kernel) => kernel.encode(+ token_ids,+ self.matrix.values(),+ output,+ batch_dim,+ self.vocab_size,+ self.embedding_dim,+ scale,+ encoder,+ ),+ LookupKernel::Quantized(kernel) => kernel.encode(+ token_ids,+ self.matrix.values(),+ self.matrix.scales().expect("quantized lookup requires scales"),+ self.matrix.zero_points(),+ self.matrix.biases(),+ output,+ self.output_hadamard_factors.as_ref(),+ batch_dim,+ self.vocab_size,+ self.embedding_dim,+ scale,+ encoder,+ ),+ }+ }+}diff --git a/crates/backend-uzu/src/encodable_block/linear/matmul.rs b/crates/backend-uzu/src/encodable_block/linear/matmul.rsindex 1d440dd54..e64f5a23c 100644--- a/crates/backend-uzu/src/encodable_block/linear/matmul.rs+++ b/crates/backend-uzu/src/encodable_block/linear/matmul.rs@@ -5,15 +5,17 @@ use crate::{array::size_for_shape,backends::common::{Allocation, Backend, Encoder,- gpu_types::{QuantizationMethod, QuantizationMode},kernel::{Kernels,matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulPath, MatmulShape},},},- config::weight_matrix::{AnyWeightMatrixSpec, Layout, int_spec::IntSpec, mlx_spec::MLXSpec},+ config::weight_matrix::{AnyWeightMatrixSpec, Layout},data_type::DataType,- encodable_block::linear::Linear,+ encodable_block::{+ linear::Linear,+ weight_matrix::{WeightMatrix, WeightMatrixError},+ },parameters::{ParameterLoaderError, ParameterTree},};@@ -23,75 +25,44 @@ pub enum LinearMatmulError<B: Backend> {BackendError(#[source] B::Error),#[error("Parameter loading error: {0}")]ParameterError(#[from] ParameterLoaderError<B>),+ #[error("Weight matrix error: {0}")]+ WeightMatrix(#[from] WeightMatrixError<B>),#[error("Unsupported data type: {0:?}")]UnsupportedDataType(DataType),#[error("Unsupported linear matmul configuration: {0}")]UnsupportedConfiguration(String),}-enum Mode<B: Backend> {- FullPrecision,- Quantized {- method: QuantizationMethod,- mode: QuantizationMode,- group_size: u32,- scales: Allocation<B>,- zero_points_or_biases: Option<Allocation<B>>,- output_hadamard_factors: Option<Allocation<B>>,- signed_codes: bool,- },-}-pub struct LinearMatmul<B: Backend> {kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- weights: Allocation<B>,+ matrix: WeightMatrix<B>,biases: Option<Allocation<B>>,+ output_hadamard_factors: Option<Allocation<B>>,input_dim: usize,output_dim: usize,output_data_type: DataType,- mode: Mode<B>,}-impl<B: Backend> LinearMatmul<B> {- pub fn full_precision(- context: &B::Context,- input_dim: usize,- output_dim: usize,- has_biases: bool,- weights_data_type: DataType,- input_data_type: DataType,- output_data_type: DataType,- parameter_tree: &ParameterTree<B>,- ) -> Result<Self, LinearMatmulError<B>> {- for data_type in [weights_data_type, input_data_type, output_data_type] {- if !matches!(data_type, DataType::BF16 | DataType::F32) {- return Err(LinearMatmulError::UnsupportedDataType(data_type));- }- }-- let weights = parameter_tree- .leaf("weights.weights")?- .validate(&[output_dim, input_dim], weights_data_type)?- .read_allocation()?;- let biases =- load_biases(weights_data_type, output_data_type, output_dim, has_biases.then_some(parameter_tree))?;-- let kernel =- <B::Kernels as Kernels>::MatmulKernel::new(context, weights_data_type, input_data_type, output_data_type)- .map_err(LinearMatmulError::BackendError)?;-- Ok(Self {- kernel: Mutex::new(kernel),- weights,- biases,- input_dim,- output_dim,- output_data_type,- mode: Mode::FullPrecision,- })+fn load_biases<B: Backend>(+ weights_data_type: DataType,+ output_data_type: DataType,+ output_dim: usize,+ parameter_tree: Option<&ParameterTree<B>>,+) -> Result<Option<Allocation<B>>, LinearMatmulError<B>> {+ if parameter_tree.is_some() && weights_data_type != output_data_type {+ return Err(LinearMatmulError::UnsupportedConfiguration(format!(+ "mixed precision linear with biases is not supported: weights={weights_data_type:?}, output={output_data_type:?}",+ )));}+ Ok(parameter_tree+ .map(|tree| tree.leaf("biases")?.validate(&[output_dim], weights_data_type)?.read_allocation())+ .transpose()?)+}- pub fn quantized(+impl<B: Backend> LinearMatmul<B> {+ /// Loads a linear over any parsed spec — full precision, MLX or Int. Hybrid+ /// compositions live in the wrappers, not here.+ pub fn load(context: &B::Context,spec: AnyWeightMatrixSpec,input_dim: usize,@@ -103,70 +74,19 @@ impl<B: Backend> LinearMatmul<B> {bias_tree: Option<&ParameterTree<B>>,output_hadamard_factors: Option<Allocation<B>>,) -> Result<Self, LinearMatmulError<B>> {- let (bits, group_size, quantization_method) = match spec {- AnyWeightMatrixSpec::MLXSpec(MLXSpec {- bits,- group_size,- layout: Layout::OutputInput,- ..- }) => (bits, group_size, QuantizationMethod::ScaleBias),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: false,- layout: Layout::OutputInput,- ..- }) => (bits, group_size, QuantizationMethod::ScaleZeroPoint),- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- is_symmetric: true,- layout: Layout::OutputInput,- ..- }) => (bits, group_size, QuantizationMethod::ScaleSymmetric),- spec => return Err(LinearMatmulError::UnsupportedConfiguration(format!("{spec:?}"))),- };-- let weight_quantization_mode = match bits {- 4 => QuantizationMode::U4,- 8 => QuantizationMode::U8,- _ => {- return Err(LinearMatmulError::UnsupportedConfiguration(format!(- "{quantization_method} bits={bits}, group_size={group_size}"- )));- },- };-for data_type in [weights_data_type, input_data_type, output_data_type] {if !matches!(data_type, DataType::BF16 | DataType::F32) {return Err(LinearMatmulError::UnsupportedDataType(data_type));}}- let packing_divisor = weight_quantization_mode.packing_divisor();- let storage_type = weight_quantization_mode.storage_type();- let k_g = input_dim.div_ceil(group_size);-- let weights = weights_tree- .leaf("weights")?- .validate(&[output_dim, input_dim / packing_divisor], storage_type)?- .read_allocation()?;- let scales = weights_tree.leaf("scales")?.validate(&[output_dim, k_g], weights_data_type)?.read_allocation()?;- let zero_points_or_biases = match quantization_method {- QuantizationMethod::ScaleBias => {- Some(weights_tree.leaf("biases")?.validate(&[output_dim, k_g], weights_data_type)?.read_allocation()?)- },- QuantizationMethod::ScaleZeroPoint => {- let expected_zero_points_entries = k_g.div_ceil(packing_divisor);- Some(- weights_tree- .leaf("zero_points")?- .validate(&[output_dim, expected_zero_points_entries], storage_type)?- .read_allocation()?,- )- },- QuantizationMethod::ScaleSymmetric => None,- };+ let matrix =+ WeightMatrix::load(weights_tree, spec, Layout::OutputInput, output_dim, input_dim, weights_data_type)?;+ if output_hadamard_factors.is_some() && matrix.quantization().is_none() {+ return Err(LinearMatmulError::UnsupportedConfiguration(+ "fused output-hadamard factors require quantized weights".into(),+ ));+ }let biases = load_biases(weights_data_type, output_data_type, output_dim, bias_tree)?;@@ -176,61 +96,17 @@ impl<B: Backend> LinearMatmul<B> {Ok(Self {kernel: Mutex::new(kernel),- weights,+ matrix,biases,+ output_hadamard_factors,input_dim,output_dim,output_data_type,- mode: Mode::Quantized {- method: quantization_method,- mode: weight_quantization_mode,- group_size: group_size as u32,- scales,- zero_points_or_biases,- output_hadamard_factors,- signed_codes: false,- },})}-}-fn load_biases<B: Backend>(- weights_data_type: DataType,- output_data_type: DataType,- output_dim: usize,- parameter_tree: Option<&ParameterTree<B>>,-) -> Result<Option<Allocation<B>>, LinearMatmulError<B>> {- if parameter_tree.is_some() && weights_data_type != output_data_type {- return Err(LinearMatmulError::UnsupportedConfiguration(format!(- "mixed precision linear with biases is not supported: weights={weights_data_type:?}, output={output_data_type:?}",- )));- }- Ok(parameter_tree- .map(|tree| tree.leaf("biases")?.validate(&[output_dim], weights_data_type)?.read_allocation())- .transpose()?)-}--impl<B: Backend> LinearMatmul<B> {- pub(super) fn make_weight_codes_signed(&mut self) {- let Mode::Quantized {- mode,- signed_codes,- ..- } = &mut self.mode- else {- return;- };- if *signed_codes {- return;- }- let Some(sign_flip_mask) = mode.weight_codes_sign_flip_mask() else {- return;- };- let broadcast_mask = u64::from(sign_flip_mask) * 0x0101_0101_0101_0101;- let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(self.weights.as_slice_mut());- words.iter_mut().for_each(|word| *word ^= broadcast_mask);- prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= sign_flip_mask);- *signed_codes = true;+ pub(super) fn make_codes_signed(&mut self) {+ self.matrix.make_codes_signed();}pub(super) fn encode_with_a(@@ -262,58 +138,13 @@ impl<B: Backend> LinearMatmul<B> {}fn matmul_b(&self) -> MatmulB<'_, B> {- match &self.mode {- Mode::FullPrecision => MatmulB::FullPrecision {- b: &self.weights,- },- Mode::Quantized {- method,- mode,- group_size,- scales,- zero_points_or_biases,- signed_codes,- ..- } => match method {- QuantizationMethod::ScaleBias => MatmulB::ScaleBiasDequant {- b: &self.weights,- scales,- biases: zero_points_or_biases.as_ref().expect("ScaleBias quantization requires biases"),- mode: *mode,- group_size: *group_size,- signed_codes: *signed_codes,- },- QuantizationMethod::ScaleZeroPoint => MatmulB::ScaleZeroPointDequant {- b: &self.weights,- scales,- zero_points: zero_points_or_biases- .as_ref()- .expect("ScaleZeroPoint quantization requires zero_points"),- mode: *mode,- group_size: *group_size,- signed_codes: *signed_codes,- },- QuantizationMethod::ScaleSymmetric => MatmulB::ScaleSymmetricDequant {- b: &self.weights,- scales,- mode: *mode,- group_size: *group_size,- signed_codes: *signed_codes,- },- },- }+ self.matrix.matmul_b()}fn d_ops(&self) -> MatmulDOps<'_, B> {MatmulDOps {bias: self.biases.as_ref(),- rht_factors: match &self.mode {- Mode::Quantized {- output_hadamard_factors: Some(factors),- ..- } => Some(factors),- _ => None,- },+ rht_factors: self.output_hadamard_factors.as_ref(),..MatmulDOps::none()}}diff --git a/crates/backend-uzu/src/encodable_block/linear/mod.rs b/crates/backend-uzu/src/encodable_block/linear/mod.rsindex 2da63d88e..1645aad6c 100644--- a/crates/backend-uzu/src/encodable_block/linear/mod.rs+++ b/crates/backend-uzu/src/encodable_block/linear/mod.rs@@ -14,11 +14,11 @@ use crate::{kernel::activation_transform::ACTIVATION_SCALE_GROUP_SIZE,},config::weight_matrix::{- AnyWeightMatrixSpec, Layout,- full_precision_spec::FullPrecisionSpec,+ AnyWeightMatrixSpec,hybrid_spec::{HybridSpec, IncoherenceProcessingMode},},data_type::DataType,+ encodable_block::weight_matrix::parse_spec,parameters::{ParameterLoaderError, ParameterTree},};@@ -72,19 +72,20 @@ impl<B: Backend> dyn Linear<B> {let weights_tree = parameter_tree.subtree("weights")?;let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;match spec {- AnyWeightMatrixSpec::FullPrecisionSpec(FullPrecisionSpec {- layout: Layout::OutputInput,- ..- }) => {- let block = LinearMatmul::full_precision(+ spec @ (AnyWeightMatrixSpec::FullPrecisionSpec(_)+ | AnyWeightMatrixSpec::MLXSpec(_)+ | AnyWeightMatrixSpec::IntSpec(_)) => {+ let block = LinearMatmul::load(context,+ spec,input_dimension,output_dimension_sum,- has_biases,weights_data_type,input_data_type,output_data_type,- parameter_tree,+ &weights_tree,+ has_biases.then_some(parameter_tree),+ None,)?;Ok(Box::new(block))},@@ -129,21 +130,6 @@ impl<B: Backend> dyn Linear<B> {&weights_tree,)?))},- spec @ (AnyWeightMatrixSpec::MLXSpec(_) | AnyWeightMatrixSpec::IntSpec(_)) => {- let block = LinearMatmul::quantized(- context,- spec,- input_dimension,- output_dimension_sum,- weights_data_type,- input_data_type,- output_data_type,- &weights_tree,- has_biases.then_some(parameter_tree),- None,- )?;- Ok(Box::new(block))- },spec => Err(LinearBlockError::UnsupportedConfiguration(format!("{spec:?}"))),}}@@ -183,7 +169,7 @@ impl<B: Backend> dyn Linear<B> {let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;match spec {spec @ (AnyWeightMatrixSpec::MLXSpec(_) | AnyWeightMatrixSpec::IntSpec(_)) => {- Ok(Box::new(LinearMatmul::quantized(+ Ok(Box::new(LinearMatmul::load(context,spec,input_dim,@@ -223,14 +209,17 @@ impl<B: Backend> dyn Linear<B> {}) = &spec{let quantization_spec = weights_tree.subtree("quantized")?.metadata::<AnyWeightMatrixSpec>("spec")?;- if int8_activations_eligible::<B>(- context,- &quantization_spec,- input_dimension,- input_data_type,- output_data_type,- ACTIVATION_SCALE_GROUP_SIZE as usize,- ) {+ let parsed = parse_spec::<B>(&quantization_spec).ok();+ if parsed.as_ref().is_some_and(|parsed| {+ int8_activations_eligible::<B>(+ context,+ parsed,+ input_dimension,+ input_data_type,+ output_data_type,+ ACTIVATION_SCALE_GROUP_SIZE as usize,+ )+ }) {let linear = RHTLinearWrapper::new(context,input_dimension,diff --git a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rsindex 6dbb4ccb9..63c222bf2 100644--- a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs+++ b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs@@ -13,7 +13,10 @@ use crate::{},config::weight_matrix::{AnyWeightMatrixSpec, hybrid_spec::IncoherenceProcessingMode, low_rank_spec::LowRankSpec},data_type::DataType,- encodable_block::linear::{Linear, LinearMatmul, LinearMatmulError},+ encodable_block::{+ linear::{Linear, LinearMatmul, LinearMatmulError},+ weight_matrix::{WeightMatrixError, parse_spec},+ },parameters::{ParameterLoaderError, ParameterTree},};@@ -21,6 +24,8 @@ use crate::{pub enum QLoRALinearWrapperError<B: Backend> {#[error("LinearMatmul error: {0}")]LinearMatmulError(#[from] LinearMatmulError<B>),+ #[error("Weight matrix error: {0}")]+ WeightMatrix(#[from] WeightMatrixError<B>),#[error("Parameter loader error: {0}")]ParameterLoaderError(#[from] ParameterLoaderError<B>),#[error("Backend error: {0}")]@@ -69,7 +74,13 @@ impl<B: Backend> QLoRALinearWrapper<B> {};let quantized_tree = weights_tree.subtree("quantized")?;- let base_linear = LinearMatmul::quantized(+ let parsed = parse_spec::<B>(&quantization_spec)?;+ let Some(_) = parsed.quantization else {+ return Err(QLoRALinearWrapperError::UnsupportedConfiguration(+ "QLoRA requires a quantized base spec".into(),+ ));+ };+ let base_linear = LinearMatmul::load(context,quantization_spec,input_dim,diff --git a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rsindex 75cfb9a2c..30cb37588 100644--- a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs+++ b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs@@ -4,7 +4,7 @@ use crate::{array::size_for_shape,backends::common::{Allocation, Backend, Context, DeviceCapabilities, Encoder,- gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,+ gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod},kernel::{ActivationTransform,activation_transform::ACTIVATION_SCALE_GROUP_SIZE,@@ -14,11 +14,12 @@ use crate::{config::weight_matrix::{AnyWeightMatrixSpec, Layout,hybrid_spec::{HybridSpec, IncoherenceProcessingMode},- int_spec::IntSpec,- mlx_spec::MLXSpec,},data_type::DataType,- encodable_block::linear::{Linear, LinearMatmul, LinearMatmulError},+ encodable_block::{+ linear::{Linear, LinearMatmul, LinearMatmulError},+ weight_matrix::{ParsedWeightSpec, WeightMatrixError, parse_spec},+ },parameters::{ParameterLoaderError, ParameterTree},};@@ -28,7 +29,7 @@ const INT8_ACTIVATIONS_ENABLED: bool = true;pub(super) fn int8_activations_eligible<B: Backend>(context: &B::Context,- quantization_spec: &AnyWeightMatrixSpec,+ spec: &ParsedWeightSpec,input_dimension: usize,input_data_type: DataType,output_data_type: DataType,@@ -43,23 +44,11 @@ pub(super) fn int8_activations_eligible<B: Backend>(if input_data_type != DataType::BF16 || output_data_type != DataType::BF16 {return false;}- let (bits, group_size) = match quantization_spec {- AnyWeightMatrixSpec::IntSpec(IntSpec {- bits,- group_size,- layout: Layout::OutputInput,- ..- })- | AnyWeightMatrixSpec::MLXSpec(MLXSpec {- bits,- group_size,- layout: Layout::OutputInput,- ..- }) => (*bits, *group_size),- _ => return false,+ let (Some(info), Layout::OutputInput) = (spec.quantization, &spec.layout) else {+ return false;};- matches!(bits, 4 | 8)- && matches!(group_size, 32 | 64 | 128)+ let group_size = info.group_size as usize;+ matches!(group_size, 32 | 64 | 128)&& input_dimension.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE)&& input_dimension.is_multiple_of(group_size)&& input_dimension.is_multiple_of(activation_group_size)@@ -69,6 +58,8 @@ pub(super) fn int8_activations_eligible<B: Backend>(pub enum RHTLinearWrapperError<B: Backend> {#[error("Inner linear error: {0}")]InnerLinearError(#[from] LinearMatmulError<B>),+ #[error("Weight matrix error: {0}")]+ WeightMatrix(#[from] WeightMatrixError<B>),#[error("Parameter loading error: {0}")]ParameterError(#[from] ParameterLoaderError<B>),#[error("Backend error: {0}")]@@ -77,16 +68,6 @@ pub enum RHTLinearWrapperError<B: Backend> {UnsupportedConfiguration(String),}-fn weights_need_group_sums(quantization_spec: &AnyWeightMatrixSpec) -> bool {- !matches!(- quantization_spec,- AnyWeightMatrixSpec::IntSpec(IntSpec {- is_symmetric: true,- ..- })- )-}-pub struct RHTLinearWrapper<B: Backend> {input_transform: ActivationTransform<B>,quantize_transform: Option<ActivationTransform<B>>,@@ -128,45 +109,16 @@ impl<B: Backend> RHTLinearWrapper<B> {.read_allocation()?;let quantized_weights_tree = weights_tree.subtree("quantized")?;let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;+ let parsed = parse_spec::<B>(&quantization_spec)?;+ let Some(quantization) = parsed.quantization else {+ return Err(RHTLinearWrapperError::UnsupportedConfiguration("RHT requires a quantized inner spec".into()));+ };let activation_group_size = ACTIVATION_SCALE_GROUP_SIZE as usize;let input_transform = ActivationTransform::input_rht(context, input_data_type, true).map_err(RHTLinearWrapperError::BackendError)?;- let quantize_transform = if int8_activations_eligible::<B>(- context,- &quantization_spec,- input_dimension,- input_data_type,- output_data_type,- activation_group_size,- ) {- let emit_group_sums = weights_need_group_sums(&quantization_spec);- let weight_group_size = match &quantization_spec {- AnyWeightMatrixSpec::IntSpec(IntSpec {- group_size,- ..- })- | AnyWeightMatrixSpec::MLXSpec(MLXSpec {- group_size,- ..- }) => *group_size,- _ => unreachable!("A8 eligibility only accepts integer quantization specs"),- };- Some(- ActivationTransform::quantize(- context,- input_data_type,- activation_group_size,- emit_group_sums.then_some((weight_group_size as u32).min(activation_group_size as u32)),- )- .map_err(RHTLinearWrapperError::BackendError)?,- )- } else {- None- };-- let mut inner_linear = LinearMatmul::quantized(+ let mut inner_linear = LinearMatmul::load(context,quantization_spec,input_dimension,@@ -178,9 +130,28 @@ impl<B: Backend> RHTLinearWrapper<B> {has_biases.then_some(parameter_tree),Some(output_factors),)?;- if quantize_transform.is_some() {- inner_linear.make_weight_codes_signed();- }++ let quantize_transform = if int8_activations_eligible::<B>(+ context,+ &parsed,+ input_dimension,+ input_data_type,+ output_data_type,+ activation_group_size,+ ) {+ let emit_group_sums = !matches!(quantization.method, QuantizationMethod::ScaleSymmetric);+ let transform = ActivationTransform::quantize(+ context,+ input_data_type,+ activation_group_size,+ emit_group_sums.then_some(quantization.group_size.min(activation_group_size as u32)),+ )+ .map_err(RHTLinearWrapperError::BackendError)?;+ inner_linear.make_codes_signed();+ Some(transform)+ } else {+ None+ };Ok(Self {input_transform,diff --git a/crates/backend-uzu/src/encodable_block/mod.rs b/crates/backend-uzu/src/encodable_block/mod.rsindex 6f9df8dd6..909d783ea 100644--- a/crates/backend-uzu/src/encodable_block/mod.rs+++ b/crates/backend-uzu/src/encodable_block/mod.rs@@ -3,6 +3,7 @@ pub mod classifier;pub mod decoder;pub mod dflash;pub mod embedding;+pub mod embedding_table;pub mod linear;pub mod mixer;pub mod mlp;@@ -14,3 +15,4 @@ pub mod transformer;pub mod transformer_layer;pub mod weaver;pub mod weaver_layer;+pub mod weight_matrix;diff --git a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rsindex ac1a4bd4c..151a3821f 100644--- a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs+++ b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs@@ -4,9 +4,7 @@ use crate::{array::size_for_shape,backends::common::{Allocation, Backend, Encoder,- kernel::{- FullPrecisionEmbeddingLookupKernel, GatedActMulKernel, Kernels, TensorAddBiasKernel, TensorAddScaleKernel,- },+ kernel::{GatedActMulKernel, Kernels, TensorAddBiasKernel, TensorAddScaleKernel},},config::{activation::AnyActivation,@@ -14,6 +12,7 @@ use crate::{},data_type::DataType,encodable_block::{+ embedding_table::{EmbeddingTable, EmbeddingTableError},linear::{Linear, LinearBlockError},normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},},@@ -30,17 +29,17 @@ pub enum PerLayerEmbeddingError<B: Backend> {Normalization(#[from] NormalizationNewError<B>),#[error("Linear error: {0}")]LinearError(#[from] LinearBlockError<B>),+ #[error("Embedding table error: {0}")]+ EmbeddingTable(#[from] EmbeddingTableError<B>),}pub struct PerLayerEmbedding<B: Backend> {- token_embedding: Allocation<B>,- token_embedding_lookup: <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel,+ token_embedding: EmbeddingTable<B>,model_projection: Box<dyn Linear<B>>,projection_norm: Normalization<B>,add_scale: <B::Kernels as Kernels>::TensorAddScaleKernel,ple_dim: usize,num_layers: usize,- ple_vocab_size: usize,model_dim: usize,fused_token_scale: f32,data_type: DataType,@@ -56,14 +55,13 @@ impl<B: Backend> PerLayerEmbedding<B> {) -> Result<Self, PerLayerEmbeddingError<B>> {let total_ple_dim = config.num_layers * config.ple_dim;- let token_embedding = parameter_tree- .leaf("token_embedding")?- .validate(&[config.ple_vocab_size, total_ple_dim], data_type)?- .read_allocation()?;-- let token_embedding_lookup =- <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)- .map_err(PerLayerEmbeddingError::BackendError)?;+ let token_embedding = EmbeddingTable::load(+ context,+ ¶meter_tree.subtree("token_embedding")?,+ config.ple_vocab_size,+ total_ple_dim,+ data_type,+ )?;let model_projection = <dyn Linear<B>>::new(model_dim,@@ -96,13 +94,11 @@ impl<B: Backend> PerLayerEmbedding<B> {Ok(Self {token_embedding,- token_embedding_lookup,model_projection,projection_norm,add_scale,ple_dim: config.ple_dim,num_layers: config.num_layers,- ple_vocab_size: config.ple_vocab_size,model_dim,fused_token_scale: config.ple_embed_scale * config.input_scale,data_type,@@ -123,13 +119,10 @@ impl<B: Backend> PerLayerEmbedding<B> {let total_elements = batch_dim * total_ple_dim;let mut token_ple = encoder.allocate_scratch(size_for_shape(&[batch_dim, total_ple_dim], self.data_type))?;- self.token_embedding_lookup.encode(+ self.token_embedding.encode_lookup(token_ids,- &self.token_embedding,&mut token_ple,batch_dim as u32,- self.ple_vocab_size as u32,- total_ple_dim as u32,self.fused_token_scale,encoder,);diff --git a/crates/backend-uzu/src/encodable_block/weight_matrix.rs b/crates/backend-uzu/src/encodable_block/weight_matrix.rsnew file mode 100644index 000000000..cfe153fcc--- /dev/null+++ b/crates/backend-uzu/src/encodable_block/weight_matrix.rs@@ -0,0 +1,253 @@+use thiserror::Error;++use crate::{+ backends::common::{+ Allocation, Backend,+ gpu_types::{QuantizationMethod, QuantizationMode},+ kernel::matmul::MatmulB,+ },+ config::weight_matrix::{AnyWeightMatrixSpec, Layout},+ data_type::DataType,+ parameters::{ParameterLoaderError, ParameterTree},+};++#[derive(Debug, Error)]+pub enum WeightMatrixError<B: Backend> {+ #[error("Parameter loading error: {0}")]+ ParameterError(#[from] ParameterLoaderError<B>),+ #[error("Unsupported weight matrix configuration: {0}")]+ UnsupportedConfiguration(String),+}++#[derive(Clone, Copy)]+pub struct QuantizationInfo {+ pub mode: QuantizationMode,+ pub method: QuantizationMethod,+ pub group_size: u32,+}++pub struct ParsedWeightSpec {+ pub layout: Layout,+ pub quantization: Option<QuantizationInfo>,+}++pub fn parse_spec<B: Backend>(spec: &AnyWeightMatrixSpec) -> Result<ParsedWeightSpec, WeightMatrixError<B>> {+ let (layout, quantized) = match spec {+ AnyWeightMatrixSpec::FullPrecisionSpec(spec) => (spec.layout.clone(), None),+ AnyWeightMatrixSpec::MLXSpec(spec) => {+ (spec.layout.clone(), Some((spec.bits, spec.group_size, QuantizationMethod::ScaleBias)))+ },+ AnyWeightMatrixSpec::IntSpec(spec) => (+ spec.layout.clone(),+ Some((+ spec.bits,+ spec.group_size,+ if spec.is_symmetric {+ QuantizationMethod::ScaleSymmetric+ } else {+ QuantizationMethod::ScaleZeroPoint+ },+ )),+ ),+ spec => return Err(WeightMatrixError::UnsupportedConfiguration(format!("{spec:?}"))),+ };+ let quantization = match quantized {+ None => None,+ Some((bits, group_size, method)) => {+ let mode = match bits {+ 4 => QuantizationMode::U4,+ 8 => QuantizationMode::U8,+ _ => {+ return Err(WeightMatrixError::UnsupportedConfiguration(format!(+ "{method} bits={bits}, group_size={group_size}"+ )));+ },+ };+ if group_size == 0 {+ return Err(WeightMatrixError::UnsupportedConfiguration("group size must be non-zero".into()));+ }+ Some(QuantizationInfo {+ mode,+ method,+ group_size: group_size as u32,+ })+ },+ };+ Ok(ParsedWeightSpec {+ layout,+ quantization,+ })+}++enum QuantizedCorrection<B: Backend> {+ Symmetric,+ Biases(Allocation<B>),+ ZeroPoints(Allocation<B>),+}++struct Quantized<B: Backend> {+ scales: Allocation<B>,+ correction: QuantizedCorrection<B>,+ info: QuantizationInfo,+ signed_codes: bool,+}++pub struct WeightMatrix<B: Backend> {+ values: Allocation<B>,+ quantized: Option<Quantized<B>>,+}++impl<B: Backend> WeightMatrix<B> {+ pub fn load(+ tree: &ParameterTree<B>,+ spec: AnyWeightMatrixSpec,+ required_layout: Layout,+ output_dim: usize,+ input_dim: usize,+ data_type: DataType,+ ) -> Result<Self, WeightMatrixError<B>> {+ let ParsedWeightSpec {+ layout,+ quantization,+ } = parse_spec(&spec)?;+ if layout != required_layout {+ return Err(WeightMatrixError::UnsupportedConfiguration(format!(+ "expected {required_layout:?} layout, got {layout:?}"+ )));+ }+ let (rows, columns) = physical_shape(&layout, output_dim, input_dim);++ let Some(info) = quantization else {+ let values = tree.leaf("weights")?.validate(&[rows, columns], data_type)?.read_allocation()?;+ return Ok(Self {+ values,+ quantized: None,+ });+ };++ let group_size = info.group_size as usize;+ let packing_divisor = info.mode.packing_divisor();+ let storage_data_type = info.mode.storage_type();+ if !columns.is_multiple_of(packing_divisor) {+ return Err(WeightMatrixError::UnsupportedConfiguration(format!(+ "stored columns {columns} are not divisible by packing divisor {packing_divisor}"+ )));+ }+ let groups = columns.div_ceil(group_size);++ let values =+ tree.leaf("weights")?.validate(&[rows, columns / packing_divisor], storage_data_type)?.read_allocation()?;+ let scales = tree.leaf("scales")?.validate(&[rows, groups], data_type)?.read_allocation()?;+ let correction = match info.method {+ QuantizationMethod::ScaleBias => QuantizedCorrection::Biases(+ tree.leaf("biases")?.validate(&[rows, groups], data_type)?.read_allocation()?,+ ),+ QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(+ tree.leaf("zero_points")?+ .validate(&[rows, groups.div_ceil(packing_divisor)], storage_data_type)?+ .read_allocation()?,+ ),+ QuantizationMethod::ScaleSymmetric => QuantizedCorrection::Symmetric,+ };++ Ok(Self {+ values,+ quantized: Some(Quantized {+ scales,+ correction,+ info,+ signed_codes: false,+ }),+ })+ }++ pub fn values(&self) -> &Allocation<B> {+ &self.values+ }++ pub fn quantization(&self) -> Option<QuantizationInfo> {+ self.quantized.as_ref().map(|quantized| quantized.info)+ }++ pub fn scales(&self) -> Option<&Allocation<B>> {+ self.quantized.as_ref().map(|quantized| &quantized.scales)+ }++ pub fn zero_points(&self) -> Option<&Allocation<B>> {+ match &self.quantized.as_ref()?.correction {+ QuantizedCorrection::ZeroPoints(zero_points) => Some(zero_points),+ QuantizedCorrection::Biases(_) | QuantizedCorrection::Symmetric => None,+ }+ }++ pub fn biases(&self) -> Option<&Allocation<B>> {+ match &self.quantized.as_ref()?.correction {+ QuantizedCorrection::Biases(biases) => Some(biases),+ QuantizedCorrection::ZeroPoints(_) | QuantizedCorrection::Symmetric => None,+ }+ }++ pub fn matmul_b(&self) -> MatmulB<'_, B> {+ let Some(quantized) = self.quantized.as_ref() else {+ return MatmulB::FullPrecision {+ b: &self.values,+ };+ };+ let mode = quantized.info.mode;+ let group_size = quantized.info.group_size;+ let signed_codes = quantized.signed_codes;+ match &quantized.correction {+ QuantizedCorrection::Biases(biases) => MatmulB::ScaleBiasDequant {+ b: &self.values,+ scales: &quantized.scales,+ biases,+ mode,+ group_size,+ signed_codes,+ },+ QuantizedCorrection::ZeroPoints(zero_points) => MatmulB::ScaleZeroPointDequant {+ b: &self.values,+ scales: &quantized.scales,+ zero_points,+ mode,+ group_size,+ signed_codes,+ },+ QuantizedCorrection::Symmetric => MatmulB::ScaleSymmetricDequant {+ b: &self.values,+ scales: &quantized.scales,+ mode,+ group_size,+ signed_codes,+ },+ }+ }++ pub fn make_codes_signed(&mut self) {+ let Some(quantized) = self.quantized.as_mut() else {+ return;+ };+ if quantized.signed_codes {+ return;+ }+ let Some(sign_flip_mask) = quantized.info.mode.weight_codes_sign_flip_mask() else {+ return;+ };+ let broadcast_mask = u64::from(sign_flip_mask) * 0x0101_0101_0101_0101;+ let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(self.values.as_slice_mut());+ words.iter_mut().for_each(|word| *word ^= broadcast_mask);+ prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= sign_flip_mask);+ quantized.signed_codes = true;+ }+}++fn physical_shape(+ layout: &Layout,+ output_dim: usize,+ input_dim: usize,+) -> (usize, usize) {+ match layout {+ Layout::OutputInput => (output_dim, input_dim),+ Layout::InputOutput => (input_dim, output_dim),+ }+}