Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Big config cleanup 1/n (#402)

uuuvn8f848a741910
diff --git a/Cargo.lock b/Cargo.lock
index 75c762d28..992fc00b7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -595,8 +595,8 @@ dependencies = [
"rustix",
"schemars 1.2.1",
"serde",
+ "serde_ignored",
"serde_json",
- "serde_json5",
"shoji",
"syn 2.0.117",
"sysinfo",
@@ -6050,6 +6050,16 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "serde_ignored"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
[[package]]
name = "serde_json"
version = "1.0.149"
@@ -6064,17 +6074,6 @@ dependencies = [
"zmij",
]
-[[package]]
-name = "serde_json5"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d34d03f54462862f2a42918391c9526337f53171eaa4d8894562be7f252edd3"
-dependencies = [
- "pest",
- "pest_derive",
- "serde",
-]
-
[[package]]
name = "serde_spanned"
version = "1.1.1"
diff --git a/Cargo.toml b/Cargo.toml
index d00d8160a..110abf4f8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -61,6 +61,7 @@ half = { version = "2.7", features = ["bytemuck", "num-traits"] }
ndarray = "0.17"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+serde_ignored = "0.1"
thiserror = "2.0"
tokenizers = { version = "0.22", features = [
"fancy-regex",
@@ -88,7 +89,6 @@ sysinfo = "0.38"
itertools = "0.14"
schemars = { version = "1.2", features = ["derive"] }
is_close = "0.1"
-serde_json5 = "0.2"
anyhow = "1.0.102"
async-trait = "0.1"
bindgen = "0.72"
diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.toml
index d31f5fbe6..c1c65d39f 100644
--- a/crates/backend-uzu/Cargo.toml
+++ b/crates/backend-uzu/Cargo.toml
@@ -16,6 +16,7 @@ half.workspace = true
ndarray.workspace = true
serde.workspace = true
serde_json.workspace = true
+serde_ignored.workspace = true
thiserror.workspace = true
tokenizers.workspace = true
rangemap.workspace = true
@@ -54,7 +55,6 @@ criterion.workspace = true
criterion-macro.workspace = true
rand_distr.workspace = true
is_close.workspace = true
-serde_json5.workspace = true
schemars.workspace = true
comfy-table.workspace = true
indicatif.workspace = true
diff --git a/crates/backend-uzu/src/array/dense.rs b/crates/backend-uzu/src/array/dense.rs
index 45ac031d2..90d11ddae 100644
--- a/crates/backend-uzu/src/array/dense.rs
+++ b/crates/backend-uzu/src/array/dense.rs
@@ -1,4 +1,4 @@
-use std::{ops::Range, os::raw::c_void, ptr::NonNull};
+use std::{os::raw::c_void, ptr::NonNull};
use ndarray::{ArrayView, Dimension, IxDyn};
@@ -41,65 +41,6 @@ impl<B: Backend, BufferRange: AsBufferRangeMut<Buffer: DenseBuffer<Backend = B>>
ArrayView::from_shape(IxDyn(self.shape()), self.as_slice::<T>()).expect("Failed to create array view")
}
- pub fn copy_from_array<
- OtherBackend: Backend,
- OtherBufferRange: AsBufferRangeMut<Buffer: DenseBuffer<Backend = OtherBackend>>,
- >(
- &mut self,
- other: &Array<OtherBackend, OtherBufferRange>,
- ) {
- assert_eq!(self.shape(), other.shape());
- assert_eq!(self.data_type(), other.data_type());
-
- self.as_bytes_mut().copy_from_slice(other.as_bytes());
- }
-
- pub fn copy_slice<
- OtherBackend: Backend,
- OtherBufferRange: AsBufferRangeMut<Buffer: DenseBuffer<Backend = OtherBackend>>,
- >(
- &mut self,
- source: &Array<OtherBackend, OtherBufferRange>,
- axis: usize,
- src_range: Range<usize>,
- dst_offset: usize,
- ) {
- assert_eq!(self.shape().len(), source.shape().len(), "Rank mismatch");
- assert!(axis < self.shape().len(), "Axis out of bounds");
- for (dimension_index, (destination_dim, source_dim)) in self.shape().iter().zip(source.shape()).enumerate() {
- if dimension_index != axis {
- assert_eq!(destination_dim, source_dim, "Shapes must match on all non-sliced axes");
- }
- }
- assert_eq!(self.data_type(), source.data_type(), "Arrays must have the same data type");
-
- let element_size = self.data_type().size_in_bytes();
- let block_size_elements = self.shape().iter().skip(axis + 1).product::<usize>();
- let block_size_bytes = block_size_elements * element_size;
- let num_blocks: usize = self.shape().iter().take(axis).product();
- let source_stride_bytes = source.shape()[axis] * block_size_bytes;
- let destination_stride_bytes = self.shape()[axis] * block_size_bytes;
-
- let rows_to_copy = src_range.end - src_range.start;
- assert!(dst_offset + rows_to_copy <= self.shape()[axis]);
- assert!(src_range.end <= source.shape()[axis]);
- let source_bytes = source.as_bytes();
- let destination_bytes = self.as_bytes_mut();
- let copy_bytes = rows_to_copy * block_size_bytes;
-
- for block_index in 0..num_blocks {
- let source_block_start = block_index * source_stride_bytes;
- let destination_block_start = block_index * destination_stride_bytes;
-
- let source_start = source_block_start + src_range.start * block_size_bytes;
- let destination_start = destination_block_start + dst_offset * block_size_bytes;
-
- let source_slice = &source_bytes[source_start..source_start + copy_bytes];
- let destination_slice = &mut destination_bytes[destination_start..destination_start + copy_bytes];
- destination_slice.copy_from_slice(source_slice);
- }
- }
-
pub fn copy_from_view<T: ArrayElement, D: Dimension>(
&mut self,
view: ArrayView<T, D>,
diff --git a/crates/backend-uzu/src/audio/context.rs b/crates/backend-uzu/src/audio/context.rs
index bcf121538..25c04ab0c 100644
--- a/crates/backend-uzu/src/audio/context.rs
+++ b/crates/backend-uzu/src/audio/context.rs
@@ -7,7 +7,6 @@ use crate::{backends::common::Backend, config::TtsConfig};
pub struct AudioGenerationContext<B: Backend> {
runtime: Rc<NanoCodecFsqRuntime<B>>,
codec_cardinality: usize,
- semantic_codec_cardinality: Option<usize>,
num_codebooks: usize,
sample_rate: u32,
}
@@ -25,7 +24,6 @@ impl<B: Backend> AudioGenerationContext<B> {
.map_err(|_| super::AudioError::Runtime("audio codec cardinality exceeds usize".to_string()))?;
Ok(Self {
codec_cardinality,
- semantic_codec_cardinality: runtime.config().semantic_codec_cardinality(),
num_codebooks: runtime.config().num_groups(),
sample_rate: runtime.config().sample_rate(),
runtime: Rc::new(runtime),
@@ -40,10 +38,6 @@ impl<B: Backend> AudioGenerationContext<B> {
self.codec_cardinality
}
- pub fn semantic_codec_cardinality(&self) -> Option<usize> {
- self.semantic_codec_cardinality
- }
-
pub fn num_codebooks(&self) -> usize {
self.num_codebooks
}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime.rs b/crates/backend-uzu/src/audio/nanocodec/runtime.rs
index 54ee95c0e..25478b74d 100644
--- a/crates/backend-uzu/src/audio/nanocodec/runtime.rs
+++ b/crates/backend-uzu/src/audio/nanocodec/runtime.rs
@@ -22,10 +22,10 @@ use crate::{
},
},
config::{
- ConfigDataType, DescriptAudioCodecConfig, DescriptAudioConvNeXtNormConfig, EmbeddingConfig,
- EmbeddingConfigCommon, InnerModelConfig, TtsAudioDecoderConfig, TtsConfig,
+ ConfigDataType, DecoderConfig, DescriptAudioCodecConfig, DescriptAudioConvNeXtNormConfig, EmbeddingConfig,
+ EmbeddingConfigCommon, TtsAudioDecoderConfig, TtsConfig,
},
- encodable_block::{Decoder, EncodingParameters, LayerExecutables, RMSNorm},
+ encodable_block::{Decoder, LayerExecutables, RMSNorm},
forward_pass::{model_shape::ModelShape, state::SharedBuffers},
parameters::ParameterLoader,
};
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
index 4b871eabd..9536a958e 100644
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
@@ -87,7 +87,7 @@ impl StructuredAudioCodecGraph {
context: Rc<B::Context>,
required_sequence_length: usize,
) -> AudioResult<StructuredAudioPostModuleRuntime<B>> {
- let inner_model_config = InnerModelConfig {
+ let decoder_config = Rc::new(DecoderConfig {
embedding_config: EmbeddingConfig::Untied {
common: EmbeddingConfigCommon {
input_scale: None,
@@ -97,10 +97,8 @@ impl StructuredAudioCodecGraph {
},
transformer_config: self.config.quantizer_config.post_module_config.clone(),
vocab_size: 1,
- };
- let decoder_config = Rc::new(inner_model_config.to_decoder_config().map_err(|_| {
- AudioError::Runtime("failed to build structured audio post_module decoder config".to_string())
- })?);
+ pard_token: None,
+ });
let model_shape = ModelShape::from_decoder_config(&decoder_config);
let weights_file = File::open(self.weights_path.as_str()).map_err(|err| {
@@ -115,7 +113,7 @@ impl StructuredAudioCodecGraph {
.subtree(transformer_subtree_name)
.map_err(|err| AudioError::Runtime(format!("missing structured audio post_module subtree: {err}")))?;
- let max_sequence_length = decoder_config.context_length.max(required_sequence_length.max(1));
+ let max_sequence_length = decoder_config.transformer_config.context_length.max(required_sequence_length.max(1));
let mut shared_buffers = SharedBuffers::new(context.as_ref(), &decoder_config, &model_shape);
{
let transformer_tree = root_loader_view
@@ -301,7 +299,6 @@ impl StructuredAudioCodecGraph {
main: Allocation<B>,
encoder: &mut Encoder<B>,
) -> AudioResult<Allocation<B>> {
- let encoding_parameters = EncodingParameters::new();
let mut main = main;
let mut shortcut = encoder
.allocate_scratch(main.as_buffer_range_ref().range().len())
@@ -326,7 +323,6 @@ impl StructuredAudioCodecGraph {
#[cfg(feature = "tracing")]
trace: None,
},
- &encoding_parameters,
main,
&mut shortcut,
encoder,
diff --git a/crates/backend-uzu/src/backends/common/activation_config.rs b/crates/backend-uzu/src/backends/common/activation_config.rs
index c054a6e52..ed4116c6e 100644
--- a/crates/backend-uzu/src/backends/common/activation_config.rs
+++ b/crates/backend-uzu/src/backends/common/activation_config.rs
@@ -7,28 +7,25 @@ use crate::backends::common::gpu_types::ActivationType;
pub enum ActivationConfig {
#[serde(rename = "SiLU")]
SILU {
- #[serde(default = "default_silu_alpha")]
alpha: f32,
},
#[serde(rename = "GELU")]
- GELU,
+ GELU {
+ approximate: bool,
+ },
#[serde(rename = "Identity")]
IDENTITY,
}
impl ActivationConfig {
- pub fn silu_default() -> ActivationConfig {
- ActivationConfig::SILU {
- alpha: 1.0,
- }
- }
-
pub fn act_type(&self) -> ActivationType {
match self {
ActivationConfig::SILU {
..
} => ActivationType::SILU,
- ActivationConfig::GELU => ActivationType::GELU,
+ ActivationConfig::GELU {
+ ..
+ } => ActivationType::GELU,
ActivationConfig::IDENTITY => ActivationType::IDENTITY,
}
}
@@ -38,12 +35,10 @@ impl ActivationConfig {
ActivationConfig::SILU {
alpha,
} => *alpha,
- ActivationConfig::GELU => 1.0,
+ ActivationConfig::GELU {
+ ..
+ } => 1.0,
ActivationConfig::IDENTITY => 1.0,
}
}
}
-
-fn default_silu_alpha() -> f32 {
- 1.0
-}
diff --git a/crates/backend-uzu/src/backends/common/kernel/audio.rs b/crates/backend-uzu/src/backends/common/kernel/audio.rs
deleted file mode 100644
index dc4e3aa63..000000000
--- a/crates/backend-uzu/src/backends/common/kernel/audio.rs
+++ /dev/null
@@ -1,187 +0,0 @@
-use crate::backends::common::{Backend, Encoder};
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum AudioPadMode {
- Zeros,
- Replicate,
-}
-
-pub struct AudioFsqDecodeArguments<'a, B: Backend> {
- pub tokens: &'a B::DenseBuffer,
- pub lengths: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub num_groups: usize,
- pub seq_len: usize,
- pub codebook_dim_per_group: usize,
- pub num_levels_per_group: &'a [i32],
-}
-
-pub struct AudioFsqEncodeArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub tokens: &'a B::DenseBuffer,
- pub lengths: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub num_groups: usize,
- pub seq_len: usize,
- pub codebook_dim_per_group: usize,
- pub num_levels_per_group: &'a [i32],
- pub dim_base_index: &'a [i32],
- pub eps: f32,
-}
-
-pub struct AudioConv1dArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub weight: &'a B::DenseBuffer,
- pub bias: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub lengths: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len_in: usize,
- pub seq_len_out: usize,
- pub kernel_size: usize,
- pub stride: usize,
- pub dilation: usize,
- pub padding: usize,
- pub pad_mode: AudioPadMode,
-}
-
-pub struct AudioCausalConv1dArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub weight: &'a B::DenseBuffer,
- pub bias: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub lengths: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len: usize,
- pub kernel_size: usize,
- pub dilation: usize,
-}
-
-pub struct AudioCausalConvTranspose1dArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub weight: &'a B::DenseBuffer,
- pub bias: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub lengths: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len_in: usize,
- pub seq_len_out: usize,
- pub stride: usize,
- pub groups: usize,
-}
-
-pub struct AudioHalfSnakeArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub alpha: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub batch_size: usize,
- pub channels: usize,
- pub seq_len: usize,
- pub snake_channels: usize,
- pub negative_slope: f32,
- pub eps: f32,
-}
-
-pub struct AudioElementwiseArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub n: usize,
-}
-
-pub struct AudioAddArguments<'a, B: Backend> {
- pub a: &'a B::DenseBuffer,
- pub b: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub n: usize,
-}
-
-pub struct AudioScaleArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub n: usize,
- pub scale: f32,
-}
-
-pub struct AudioClampArguments<'a, B: Backend> {
- pub input: &'a B::DenseBuffer,
- pub output: &'a B::DenseBuffer,
- pub n: usize,
- pub min_value: f32,
- pub max_value: f32,
-}
-
-pub trait AudioKernelRuntime<B: Backend> {
- fn encode_fsq_decode(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioFsqDecodeArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_fsq_encode(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioFsqEncodeArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_conv1d(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioConv1dArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_causal_conv1d(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioCausalConv1dArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_causal_conv_transpose1d(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioCausalConvTranspose1dArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_half_snake(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioHalfSnakeArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_leaky_relu(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioElementwiseArguments<B>,
- negative_slope: f32,
- ) -> Result<(), B::Error>;
-
- fn encode_tanh(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioElementwiseArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_add(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioAddArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_scale(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioScaleArguments<B>,
- ) -> Result<(), B::Error>;
-
- fn encode_clamp(
- &self,
- encoder: &mut Encoder<B>,
- arguments: AudioClampArguments<B>,
- ) -> Result<(), B::Error>;
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/mod.rs
deleted file mode 100644
index b68fab06e..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod shaders;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/gemv.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/gemv.rs
deleted file mode 100644
index 952e0c684..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/gemv.rs
+++ /dev/null
@@ -1,103 +0,0 @@
-use num_traits::Float;
-
-use crate::{
- ArrayElement,
- utils::pointers::{SendPtr, SendPtrMut},
-};
-
-#[inline(always)]
-unsafe fn compute_gemv_rows<T: ArrayElement + Float>(
- mat: SendPtr<T>,
- vec_row: SendPtr<T>,
- out_row: SendPtrMut<T>,
- src: Option<SendPtr<T>>,
- out_start: usize,
- out_end: usize,
- in_dim: usize,
- mat_ld: usize,
- output_scale: f32,
- output_accumulate_scale: f32,
- output_source_stride: usize,
- apply_output_scale_and_accumulate: bool,
-) {
- unsafe {
- for out_idx in out_start..out_end {
- let mat_row = mat.0.add(out_idx * mat_ld);
-
- let mut acc: f32 = 0.0;
- for in_idx in 0..in_dim {
- acc += (*mat_row.add(in_idx)).to_f32().unwrap() * (*vec_row.0.add(in_idx)).to_f32().unwrap();
- }
-
- if apply_output_scale_and_accumulate {
- if let Some(s) = src {
- let src_val = (*s.0.add(out_idx * output_source_stride)).to_f32().unwrap();
- acc = output_scale * acc + output_accumulate_scale * src_val;
- }
- }
-
- *out_row.0.add(out_idx) = T::from(acc).unwrap();
- }
- }
-}
-
-pub fn matmul_gemv_impl<T: ArrayElement + Float>(
- matrix: *const T,
- input_vector: *const T,
- output_source: Option<*const T>,
- output_vector: *mut T,
- input_dimension: usize,
- output_dimension: usize,
- matrix_leading_dimension: usize,
- output_scale: f32,
- output_accumulate_scale: f32,
- output_source_stride: usize,
- batch_rows: usize,
- apply_output_scale_and_accumulate: bool,
-) {
- let num_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
- let matrix = SendPtr(matrix);
- let output_source = output_source.map(SendPtr);
-
- unsafe {
- for batch_row in 0..batch_rows {
- let vec_row = SendPtr(input_vector.add(batch_row * input_dimension));
- let out_row = SendPtrMut(output_vector.add(batch_row * output_dimension));
-
- std::thread::scope(|s| {
- let rows_per_thread = output_dimension / num_threads;
- let rows_per_thread_remainder = output_dimension % num_threads;
- let mut start = 0;
-
- for t in 0..num_threads {
- let chunk = rows_per_thread
- + if t < rows_per_thread_remainder {
- 1
- } else {
- 0
- };
- let end = start + chunk;
-
- s.spawn(move || unsafe {
- compute_gemv_rows(
- matrix,
- vec_row,
- out_row,
- output_source,
- start,
- end,
- input_dimension,
- matrix_leading_dimension,
- output_scale,
- output_accumulate_scale,
- output_source_stride,
- apply_output_scale_and_accumulate,
- );
- });
-
- start = end;
- }
- });
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/mod.rs
deleted file mode 100644
index fc35204af..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/gemv/shaders/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod gemv;
diff --git a/crates/backend-uzu/src/classifier/classifier.rs b/crates/backend-uzu/src/classifier/classifier.rs
index 7683b416a..98e23913b 100644
--- a/crates/backend-uzu/src/classifier/classifier.rs
+++ b/crates/backend-uzu/src/classifier/classifier.rs
@@ -6,8 +6,8 @@ use super::{ClassificationOutput, ClassificationStats, ClassifierContext};
use crate::{
DataType, allocation_to_vec,
backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder},
- config::ModelMetadata,
- encodable_block::{EncodingParameters, LayerArguments},
+ config::{ClassifierModelConfig, ModelMetadata},
+ encodable_block::LayerArguments,
forward_pass::token_inputs::TokenInputs,
session::types::Error,
};
@@ -67,7 +67,7 @@ impl<B: Backend> ClassifierTrait for Classifier<B> {
impl<B: Backend> Classifier<B> {
pub fn new(
model_path: &Path,
- model_metadata: &ModelMetadata,
+ model_metadata: &ModelMetadata<ClassifierModelConfig>,
) -> Result<Self, Error> {
let context = ClassifierContext::new(model_path, model_metadata)?;
Ok(Self {
@@ -109,7 +109,6 @@ impl<B: Backend> Classifier<B> {
) -> Result<Box<[f32]>, Error> {
let batch_dim = token_ids.len();
let token_inputs = TokenInputs::new_classifier(self.context.context.as_ref(), token_ids, token_positions);
- let encoding_params = EncodingParameters::new();
#[cfg(feature = "tracing")]
let mut trace = trace;
@@ -155,7 +154,6 @@ impl<B: Backend> Classifier<B> {
#[cfg(feature = "tracing")]
trace: trace.as_deref_mut().map(|traces| &mut traces.layer_results[layer_index]),
},
- &encoding_params,
main,
&mut shortcut,
&mut encoder,
diff --git a/crates/backend-uzu/src/classifier/classifier_context.rs b/crates/backend-uzu/src/classifier/classifier_context.rs
index b526b8884..382584316 100644
--- a/crates/backend-uzu/src/classifier/classifier_context.rs
+++ b/crates/backend-uzu/src/classifier/classifier_context.rs
@@ -34,14 +34,16 @@ pub struct ClassifierContext<B: Backend> {
impl<B: Backend> ClassifierContext<B> {
pub fn new(
model_path: &Path,
- model_metadata: &ModelMetadata,
+ model_metadata: &ModelMetadata<ClassifierModelConfig>,
) -> Result<Self, Error> {
let context = B::Context::new().map_err(|e| Error::UnableToCreateContext(e.into()))?;
- let classifier_model_config = model_metadata.model_config.as_classifier().ok_or(Error::UnableToLoadConfig)?;
-
- let decoder_config =
- Rc::new(classifier_model_config.model_config.to_decoder_config().map_err(|_| Error::UnableToLoadConfig)?);
+ let decoder_config = Rc::new(crate::config::DecoderConfig {
+ embedding_config: model_metadata.model_config.model_config.embedding_config.clone(),
+ transformer_config: model_metadata.model_config.model_config.transformer_config.clone(),
+ vocab_size: model_metadata.model_config.model_config.vocab_size,
+ pard_token: None,
+ });
let model_shape = ModelShape::from_decoder_config(&decoder_config);
let weights_path = model_path.join("model.safetensors");
@@ -53,22 +55,15 @@ impl<B: Backend> ClassifierContext<B> {
let root_loader_view = loader.tree();
let mut shared_buffers = SharedBuffers::new(context.as_ref(), &decoder_config, &model_shape);
+ shared_buffers.update_data(&root_loader_view);
+ let shared_buffers = Rc::new(shared_buffers);
+
let transformer_tree = root_loader_view
.subtree("transformer")
.map_err(|_| Error::Classifier(ClassifierError::WeightSubtreeNotFound("transformer".to_string())))?;
- if let Some(global_rope) = &mut shared_buffers.global_rope {
- global_rope.update_data(&transformer_tree, "global_rope");
- }
- if let Some(local_rope) = &mut shared_buffers.local_rope {
- local_rope.update_data(&transformer_tree, "local_rope");
- }
- let shared_buffers = Rc::new(shared_buffers);
-
let data_type = decoder_config
- .layer_config
- .mixer_config
- .as_attention()
+ .first_attention()
.ok_or(Error::Classifier(ClassifierError::NonAttentionMixer))?
.qkv_projection_config
.activation_precision()
@@ -77,14 +72,15 @@ impl<B: Backend> ClassifierContext<B> {
let embed = Embedding::new(
context.as_ref(),
decoder_config.vocab_size as u32,
- decoder_config.model_dim as u32,
+ decoder_config.transformer_config.model_dim as u32,
&decoder_config.embedding_config,
&root_loader_view.subtree("embedding").expect("Failed to get embedding subtree"),
)
.expect("Failed to create embedding");
let global_rope = Self::create_rope_block(&context, data_type, RopeType::Global).map_err(Error::Classifier)?;
- let local_rope = classifier_model_config
+ let local_rope = model_metadata
+ .model_config
.model_config
.transformer_config
.local_rope_config
@@ -93,46 +89,30 @@ impl<B: Backend> ClassifierContext<B> {
.transpose()
.map_err(Error::Classifier)?;
- let layers = classifier_model_config
+ let layers = model_metadata
+ .model_config
.model_config
.transformer_config
.layer_configs
.iter()
.enumerate()
.map(|(layer_index, layer_config)| {
- let mut rope = global_rope.clone();
- let attn = layer_config.attention_config().ok_or(ClassifierError::NonAttentionMixer)?;
-
- if attn.sliding_window_size.is_some() {
- if let Some(local_rope_block) = local_rope.clone() {
- rope = local_rope_block;
- }
- }
-
- let num_heads = attn.num_heads.ok_or_else(|| {
- ClassifierError::MissingConfigField(format!("num_heads in layer {}", layer_index))
- })?;
- let head_dim = attn
- .head_dim
- .ok_or_else(|| ClassifierError::MissingConfigField(format!("head_dim in layer {}", layer_index)))?;
- let num_groups = attn.num_groups.ok_or_else(|| {
- ClassifierError::MissingConfigField(format!("num_groups in layer {}", layer_index))
- })?;
+ let attn = layer_config.mixer_config.as_attention().ok_or(ClassifierError::NonAttentionMixer)?;
+ let rope = if attn.sliding_window_size.is_some() && local_rope.is_some() {
+ local_rope.clone().unwrap()
+ } else {
+ global_rope.clone()
+ };
let layer_tree = transformer_tree
.subtree(&format!("layers.{}", layer_index))
.map_err(|_| ClassifierError::WeightSubtreeNotFound(format!("layers.{}", layer_index)))?;
Ok(ClassifierLayer::new(
- context.clone(),
+ context.as_ref(),
+ &model_metadata.model_config.model_config.transformer_config,
layer_config,
layer_index,
- classifier_model_config.model_config.model_dim,
- classifier_model_config.model_config.transformer_config.hidden_dim,
- num_heads,
- head_dim,
- num_groups,
- attn.scale,
&layer_tree,
rope,
))
@@ -147,7 +127,7 @@ impl<B: Backend> ClassifierContext<B> {
let output_norm = Normalization::new(
context.as_ref(),
data_type,
- classifier_model_config.model_config.transformer_config.output_norm_config.clone(),
+ model_metadata.model_config.model_config.transformer_config.output_norm_config.clone(),
&output_norm_tree,
)
.map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("output norm: {:?}", e))))?;
@@ -158,14 +138,14 @@ impl<B: Backend> ClassifierContext<B> {
let embedding_norm = Normalization::new(
context.as_ref(),
data_type,
- classifier_model_config.model_config.embedding_norm_config.clone(),
+ model_metadata.model_config.model_config.embedding_norm_config.clone(),
&embedding_norm_tree,
)
.map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("embedding norm: {:?}", e))))?;
- let model_dim = classifier_model_config.model_config.model_dim;
- let num_labels = classifier_model_config.model_config.num_labels;
- let prediction_head_config = &classifier_model_config.model_config.prediction_head_config;
+ let model_dim = model_metadata.model_config.model_config.model_dim;
+ let num_labels = model_metadata.model_config.model_config.num_labels;
+ let prediction_head_config = &model_metadata.model_config.model_config.prediction_head_config;
let prediction_head_tree = root_loader_view
.subtree("prediction_head")
.map_err(|_| Error::Classifier(ClassifierError::WeightSubtreeNotFound("prediction_head".to_string())))?;
@@ -216,7 +196,7 @@ impl<B: Backend> ClassifierContext<B> {
let pooling = Pooling::<B>::new(
context.as_ref(),
data_type,
- classifier_model_config.model_config.classifier_pooling.clone(),
+ model_metadata.model_config.model_config.classifier_pooling.clone(),
model_dim,
)
.map_err(|e| {
@@ -240,7 +220,7 @@ impl<B: Backend> ClassifierContext<B> {
Ok(Self {
context,
shared_buffers,
- model_config: classifier_model_config.clone(),
+ model_config: model_metadata.model_config.clone(),
model_shape,
embed,
embedding_norm,
diff --git a/crates/backend-uzu/src/config/attention.rs b/crates/backend-uzu/src/config/attention.rs
index 63d8e4e68..061dde769 100644
--- a/crates/backend-uzu/src/config/attention.rs
+++ b/crates/backend-uzu/src/config/attention.rs
@@ -10,27 +10,18 @@ pub struct AttentionConfig {
pub query_norm_config: Option<NormalizationConfig>,
pub key_norm_config: Option<NormalizationConfig>,
- pub num_heads: Option<usize>,
- pub num_groups: Option<usize>,
- pub head_dim: Option<usize>,
- pub is_causal: Option<bool>,
+ pub num_heads: usize,
+ pub num_groups: usize,
+ pub head_dim: usize,
+ pub is_causal: bool,
pub scale: Option<f32>,
pub sliding_window_size: Option<usize>,
pub logit_soft_cap: Option<f32>,
- #[serde(default)]
pub has_sinks: bool,
pub has_qkv_biases: bool,
pub has_out_biases: bool,
- #[serde(default)]
- pub has_gate: bool,
- #[serde(default)]
pub gate_projection_config: Option<LinearConfig>,
pub use_rope: bool,
- #[serde(default)]
pub partial_rope_dim: Option<usize>,
}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/attention_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/classifier/classifier_config.rs b/crates/backend-uzu/src/config/classifier/classifier_config.rs
index 8386ac012..9d3015e7b 100644
--- a/crates/backend-uzu/src/config/classifier/classifier_config.rs
+++ b/crates/backend-uzu/src/config/classifier/classifier_config.rs
@@ -1,10 +1,7 @@
use serde::{Deserialize, Serialize};
use super::{PoolingType, PredictionHeadConfig};
-use crate::config::{
- ConfigError, DecoderConfig, DecoderLayerConfig, EmbeddingConfig, LinearConfig, NormalizationConfig,
- TransformerConfig,
-};
+use crate::config::{EmbeddingConfig, LinearConfig, NormalizationConfig, TransformerConfig};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ClassifierConfig {
@@ -13,86 +10,13 @@ pub struct ClassifierConfig {
pub transformer_config: TransformerConfig,
pub prediction_head_config: PredictionHeadConfig,
pub readout_config: LinearConfig,
-
pub vocab_size: usize,
pub model_dim: usize,
pub hidden_dim: usize,
- #[serde(default)]
- pub num_heads: Option<usize>,
- #[serde(default)]
- pub num_groups: Option<usize>,
- #[serde(default)]
- pub head_dim: Option<usize>,
pub attention_scale: Option<f32>,
pub num_layers: usize,
- #[serde(default)]
- pub sliding_window_sizes: Option<Vec<Option<usize>>>,
pub context_length: usize,
pub num_labels: usize,
pub classifier_pooling: PoolingType,
pub output_labels: Option<Vec<String>>,
}
-
-impl ClassifierConfig {
- pub fn to_decoder_config(&self) -> Result<DecoderConfig, ConfigError> {
- // For classifier, we use the first layer config as the template
- // (most classifiers have homogeneous layers)
- let first_layer = self.transformer_config.layer_configs.first().ok_or(ConfigError::NoLayers)?;
-
- let layer_config = DecoderLayerConfig {
- pre_attention_norm_config: first_layer.pre_attention_norm_config.clone().unwrap_or_else(|| {
- // If first layer has no pre-attention norm (like ModernBERT), use a default
- self.transformer_config.output_norm_config.clone()
- }),
- mixer_config: first_layer.mixer_config.clone(),
- post_attention_norm_config: first_layer.post_attention_norm_config.clone(),
- pre_mlp_norm_config: first_layer.pre_mlp_norm_config.clone(),
- mlp_config: first_layer.mlp_config.clone(),
- post_mlp_norm_config: first_layer.post_mlp_norm_config.clone(),
- };
-
- let first_mixer = &first_layer.mixer_config;
-
- let num_heads = self
- .num_heads
- .or(first_mixer.num_heads())
- .ok_or_else(|| ConfigError::MissingField("num_heads".to_string()))?;
- let num_groups = self.num_groups.or(first_mixer.num_groups()).unwrap_or(num_heads);
- let head_dim = self
- .head_dim
- .or(first_mixer.head_dim())
- .ok_or_else(|| ConfigError::MissingField("head_dim".to_string()))?;
-
- Ok(DecoderConfig {
- embedding_config: self.embedding_config.clone(),
- global_rope_config: self.transformer_config.global_rope_config.clone(),
- local_rope_config: self.transformer_config.local_rope_config.clone(),
- layer_config,
- output_norm_config: self.transformer_config.output_norm_config.clone(),
- vocab_size: self.vocab_size,
- model_dim: self.model_dim,
- hidden_dim: self.transformer_config.hidden_dim,
- num_heads,
- num_groups,
- head_dim,
- attention_scale: self.attention_scale,
- num_layers: self.num_layers,
- sliding_window_sizes: {
- if let Some(sizes) = &self.sliding_window_sizes {
- Some(sizes.clone().into_boxed_slice())
- } else {
- let sizes: Vec<Option<usize>> = self
- .transformer_config
- .layer_configs
- .iter()
- .map(|layer| layer.mixer_config.sliding_window_size())
- .collect();
- Some(sizes.into_boxed_slice())
- }
- },
- context_length: self.context_length,
- layer_configs: None, // Classifier doesn't use heterogeneous layers usually
- layer_types: None,
- })
- }
-}
diff --git a/crates/backend-uzu/src/config/decoder.rs b/crates/backend-uzu/src/config/decoder.rs
index 2f742710a..4cf547e35 100644
--- a/crates/backend-uzu/src/config/decoder.rs
+++ b/crates/backend-uzu/src/config/decoder.rs
@@ -1,244 +1,17 @@
-use serde::{
- Deserialize, Serialize,
- de::{self, Deserializer},
-};
+use serde::{Deserialize, Serialize};
-use super::{
- decoder_layer::{DecoderLayerConfig, MixerConfig},
- embedding::EmbeddingConfig,
- normalization::NormalizationConfig,
- rope::RoPEConfig,
-};
+use super::{AttentionConfig, EmbeddingConfig, TransformerConfig};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-#[serde(tag = "type", rename_all = "snake_case")]
-pub enum DecoderLayerType {
- Transformer,
- #[serde(rename = "ssm")]
- StateSpace {
- conv_dim: usize,
- kernel_size: usize,
- state_dim: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- },
- #[serde(rename = "short_conv")]
- ShortConv {
- kernel_size: usize,
- },
- #[serde(rename = "delta_net")]
- DeltaNet {
- conv_dim: usize,
- kernel_size: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- value_head_dim: usize,
- },
-}
-
-#[derive(Debug, Serialize, PartialEq, Clone)]
pub struct DecoderConfig {
pub embedding_config: EmbeddingConfig,
- pub global_rope_config: Option<RoPEConfig>,
- pub local_rope_config: Option<RoPEConfig>,
- pub layer_config: DecoderLayerConfig,
- pub layer_configs: Option<Box<[DecoderLayerConfig]>>,
- pub output_norm_config: NormalizationConfig,
-
+ pub transformer_config: TransformerConfig,
pub vocab_size: usize,
- pub model_dim: usize,
- pub hidden_dim: usize,
- pub num_heads: usize,
- pub num_groups: usize,
- pub head_dim: usize,
- pub attention_scale: Option<f32>,
- pub num_layers: usize,
- pub sliding_window_sizes: Option<Box<[Option<usize>]>>,
- pub layer_types: Option<Box<[DecoderLayerType]>>,
- pub context_length: usize,
+ pub pard_token: Option<usize>,
}
-impl<'de> Deserialize<'de> for DecoderConfig {
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where
- D: Deserializer<'de>,
- {
- let raw = RawDecoderConfig::deserialize(deserializer)?;
- let RawDecoderConfig {
- embedding_config,
- global_rope_config,
- local_rope_config,
- layer_config,
- layer_configs,
- output_norm_config,
- vocab_size,
- model_dim,
- hidden_dim,
- num_heads,
- num_groups,
- head_dim,
- attention_scale,
- num_layers,
- sliding_window_sizes,
- layer_types,
- context_length,
- } = raw;
-
- let layer_configs_boxed = layer_configs.map(|layers| layers.into_boxed_slice());
-
- let layer_config_value = if let Some(config) = layer_config {
- config
- } else if let Some(configs) = layer_configs_boxed.as_ref() {
- configs.first().cloned().ok_or_else(|| de::Error::custom("layer_configs must not be empty"))?
- } else {
- return Err(de::Error::custom("decoder config must include layer_config or layer_configs"));
- };
-
- let num_layers_value = if let Some(value) = num_layers {
- value
- } else if let Some(configs) = layer_configs_boxed.as_ref() {
- configs.len()
- } else {
- return Err(de::Error::custom("num_layers missing and layer_configs not provided"));
- };
-
- let (num_heads_value, num_groups_value, head_dim_value) = match (num_heads, num_groups, head_dim) {
- (Some(h), Some(g), Some(d)) => (h, g, d),
- _ => derive_dims_from_layer(&layer_config_value).ok_or_else(|| {
- de::Error::custom(
- "num_heads/num_groups/head_dim missing and \
- cannot be derived from layer config",
- )
- })?,
- };
-
- let attention_scale_value = if attention_scale.is_some() {
- attention_scale
- } else {
- layer_config_value.mixer_config.attention_scale()
- };
-
- let sliding_window_sizes_boxed = if let Some(sizes) = sliding_window_sizes {
- Some(sizes.into_boxed_slice())
- } else if let Some(configs) = layer_configs_boxed.as_ref() {
- Some(
- configs
- .iter()
- .map(|layer| layer.mixer_config.sliding_window_size())
- .collect::<Vec<_>>()
- .into_boxed_slice(),
- )
- } else {
- None
- };
-
- let explicit_layer_types = layer_types.map(|types| types.into_boxed_slice());
- let derived_layer_types = if let Some(configs) = layer_configs_boxed.as_ref() {
- Some(configs.iter().map(layer_type_from_config).collect::<Vec<_>>().into_boxed_slice())
- } else {
- None
- };
- let layer_types_value = explicit_layer_types.or(derived_layer_types);
-
- Ok(Self {
- embedding_config,
- global_rope_config,
- local_rope_config,
- layer_config: layer_config_value,
- layer_configs: layer_configs_boxed,
- output_norm_config,
- vocab_size,
- model_dim,
- hidden_dim,
- num_heads: num_heads_value,
- num_groups: num_groups_value,
- head_dim: head_dim_value,
- attention_scale: attention_scale_value,
- num_layers: num_layers_value,
- sliding_window_sizes: sliding_window_sizes_boxed,
- layer_types: layer_types_value,
- context_length,
- })
- }
-}
-
-#[derive(Deserialize)]
-struct RawDecoderConfig {
- embedding_config: EmbeddingConfig,
- #[serde(default)]
- global_rope_config: Option<RoPEConfig>,
- #[serde(default)]
- local_rope_config: Option<RoPEConfig>,
- #[serde(default)]
- layer_config: Option<DecoderLayerConfig>,
- #[serde(default)]
- layer_configs: Option<Vec<DecoderLayerConfig>>,
- output_norm_config: NormalizationConfig,
- vocab_size: usize,
- model_dim: usize,
- hidden_dim: usize,
- #[serde(default)]
- num_heads: Option<usize>,
- #[serde(default)]
- num_groups: Option<usize>,
- #[serde(default)]
- head_dim: Option<usize>,
- #[serde(default)]
- attention_scale: Option<f32>,
- #[serde(default)]
- num_layers: Option<usize>,
- #[serde(default)]
- sliding_window_sizes: Option<Vec<Option<usize>>>,
- #[serde(default)]
- layer_types: Option<Vec<DecoderLayerType>>,
- context_length: usize,
-}
-
-fn derive_dims_from_layer(layer: &DecoderLayerConfig) -> Option<(usize, usize, usize)> {
- Some((layer.mixer_config.num_heads()?, layer.mixer_config.num_groups()?, layer.mixer_config.head_dim()?))
-}
-
-fn layer_type_from_config(layer: &DecoderLayerConfig) -> DecoderLayerType {
- match &layer.mixer_config {
- MixerConfig::Attention(_) => DecoderLayerType::Transformer,
- MixerConfig::Mamba(config) => DecoderLayerType::StateSpace {
- conv_dim: config.conv_dim(),
- kernel_size: config.kernel_size,
- state_dim: config.state_dim,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- head_dim: config.head_dim,
- },
- MixerConfig::ShortConv(config) => DecoderLayerType::ShortConv {
- kernel_size: config.kernel_size,
- },
- MixerConfig::DeltaNet(config) => DecoderLayerType::DeltaNet {
- conv_dim: config.conv_dim(),
- kernel_size: config.kernel_size,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- head_dim: config.head_dim,
- value_head_dim: config.value_head_dim,
- },
- }
-}
impl DecoderConfig {
- pub fn group_size(&self) -> usize {
- self.num_heads * self.num_groups
- }
-
- pub fn has_attention_layers(&self) -> bool {
- self.layer_configs
- .as_ref()
- .map(|configs| {
- configs.iter().any(|config| matches!(config.mixer_config, crate::config::MixerConfig::Attention(_)))
- })
- .unwrap_or(true)
+ pub fn first_attention(&self) -> Option<&AttentionConfig> {
+ self.transformer_config.layer_configs.iter().find_map(|l| l.mixer_config.as_attention())
}
}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/decoder_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/decoder_layer.rs b/crates/backend-uzu/src/config/decoder_layer.rs
deleted file mode 100644
index dfae7f443..000000000
--- a/crates/backend-uzu/src/config/decoder_layer.rs
+++ /dev/null
@@ -1,115 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-use super::{
- attention::AttentionConfig, delta_net::DeltaNetAttentionConfig, mamba::Mamba2Config, mlp::MLPConfig,
- normalization::NormalizationConfig, short_conv::ShortConvConfig,
-};
-
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-#[serde(tag = "type")]
-pub enum MixerConfig {
- #[serde(rename = "AttentionConfig")]
- Attention(AttentionConfig),
- #[serde(rename = "Mamba2Config")]
- Mamba(Mamba2Config),
- #[serde(rename = "ShortConvConfig")]
- ShortConv(ShortConvConfig),
- #[serde(rename = "DeltaNetAttentionConfig")]
- DeltaNet(DeltaNetAttentionConfig),
-}
-
-impl MixerConfig {
- pub fn as_attention(&self) -> Option<&AttentionConfig> {
- match self {
- MixerConfig::Attention(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn as_mamba(&self) -> Option<&Mamba2Config> {
- match self {
- MixerConfig::Mamba(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn as_short_conv(&self) -> Option<&ShortConvConfig> {
- match self {
- MixerConfig::ShortConv(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn as_delta_net(&self) -> Option<&DeltaNetAttentionConfig> {
- match self {
- MixerConfig::DeltaNet(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn num_heads(&self) -> Option<usize> {
- match self {
- MixerConfig::Attention(config) => config.num_heads,
- MixerConfig::Mamba(config) => Some(config.num_heads),
- MixerConfig::ShortConv(_) => None,
- MixerConfig::DeltaNet(config) => Some(config.num_heads),
- }
- }
-
- pub fn num_groups(&self) -> Option<usize> {
- match self {
- MixerConfig::Attention(config) => config.num_groups,
- MixerConfig::Mamba(config) => Some(config.num_groups),
- MixerConfig::ShortConv(_) => None,
- MixerConfig::DeltaNet(config) => Some(config.num_groups),
- }
- }
-
- pub fn head_dim(&self) -> Option<usize> {
- match self {
- MixerConfig::Attention(config) => config.head_dim,
- MixerConfig::Mamba(config) => Some(config.head_dim),
- MixerConfig::ShortConv(_) => None,
- MixerConfig::DeltaNet(config) => Some(config.head_dim),
- }
- }
-
- pub fn sliding_window_size(&self) -> Option<usize> {
- match self {
- MixerConfig::Attention(config) => config.sliding_window_size,
- MixerConfig::Mamba(_) | MixerConfig::ShortConv(_) | MixerConfig::DeltaNet(_) => None,
- }
- }
-
- pub fn attention_scale(&self) -> Option<f32> {
- match self {
- MixerConfig::Attention(config) => config.scale,
- MixerConfig::Mamba(_) | MixerConfig::ShortConv(_) | MixerConfig::DeltaNet(_) => None,
- }
- }
-}
-
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct DecoderLayerConfig {
- #[serde(alias = "pre_mixer_norm_config")]
- pub pre_attention_norm_config: NormalizationConfig,
- #[serde(alias = "mixer_config")]
- pub mixer_config: MixerConfig,
- #[serde(alias = "post_mixer_norm_config")]
- pub post_attention_norm_config: Option<NormalizationConfig>,
- #[serde(alias = "pre_mlp_norm_config")]
- pub pre_mlp_norm_config: NormalizationConfig,
- pub mlp_config: MLPConfig,
- #[serde(alias = "post_mlp_norm_config")]
- pub post_mlp_norm_config: Option<NormalizationConfig>,
-}
-
-impl DecoderLayerConfig {
- pub fn attention_config(&self) -> Option<&AttentionConfig> {
- self.mixer_config.as_attention()
- }
-}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/decoder_layer_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/embedding.rs b/crates/backend-uzu/src/config/embedding.rs
index 78d79de4c..ff1a5c698 100644
--- a/crates/backend-uzu/src/config/embedding.rs
+++ b/crates/backend-uzu/src/config/embedding.rs
@@ -58,27 +58,48 @@ impl EmbeddingConfig {
EmbeddingConfig::Tied {
common,
..
- } => common,
- EmbeddingConfig::Untied {
+ }
+ | EmbeddingConfig::Untied {
common,
..
- } => common,
- EmbeddingConfig::MLXQuantizedTied {
+ }
+ | EmbeddingConfig::MLXQuantizedTied {
common,
..
- } => common,
- EmbeddingConfig::MLXQuantizedUntied {
+ }
+ | EmbeddingConfig::MLXQuantizedUntied {
common,
..
- } => common,
- EmbeddingConfig::MLXSemiQuantizedUntied {
+ }
+ | EmbeddingConfig::MLXSemiQuantizedUntied {
common,
..
} => common,
}
}
-}
-#[cfg(test)]
-#[path = "../../tests/unit/config/embedding_test.rs"]
-mod tests;
+ pub fn activation_precision(&self) -> ConfigDataType {
+ match self {
+ EmbeddingConfig::Tied {
+ precision,
+ ..
+ }
+ | EmbeddingConfig::Untied {
+ precision,
+ ..
+ } => *precision,
+ EmbeddingConfig::MLXQuantizedTied {
+ activation_precision,
+ ..
+ }
+ | EmbeddingConfig::MLXQuantizedUntied {
+ activation_precision,
+ ..
+ }
+ | EmbeddingConfig::MLXSemiQuantizedUntied {
+ activation_precision,
+ ..
+ } => *activation_precision,
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/config/error.rs b/crates/backend-uzu/src/config/error.rs
deleted file mode 100644
index aed9c0118..000000000
--- a/crates/backend-uzu/src/config/error.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use thiserror::Error;
-
-#[derive(Debug, Error)]
-pub enum ConfigError {
- #[error("Missing required field: {0}")]
- MissingField(String),
- #[error("No layers in transformer config")]
- NoLayers,
-}
diff --git a/crates/backend-uzu/src/config/language_model.rs b/crates/backend-uzu/src/config/language_model.rs
index 071a36ccd..4c485eb67 100644
--- a/crates/backend-uzu/src/config/language_model.rs
+++ b/crates/backend-uzu/src/config/language_model.rs
@@ -1,184 +1,10 @@
use serde::{Deserialize, Serialize};
-use crate::config::{
- ConfigError, DecoderConfig, DecoderLayerConfig, DecoderLayerType, EmbeddingConfig, GenerationConfig,
- MessageProcessorConfig, MixerConfig, TransformerConfig,
-};
-
-struct AttentionDims {
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- attention_scale: Option<f32>,
-}
-
-/// Inner model config matching the new lalamo export format.
-/// Contains embedding_config at the top level, with transformer_config nested.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct InnerModelConfig {
- pub embedding_config: EmbeddingConfig,
- pub transformer_config: TransformerConfig,
- pub vocab_size: usize,
-}
-
-impl InnerModelConfig {
- /// Convert to DecoderConfig for backward compatibility with the rest of the codebase.
- pub fn to_decoder_config(&self) -> Result<DecoderConfig, ConfigError> {
- let tf = &self.transformer_config;
-
- let first_layer = tf.layer_configs.first().ok_or(ConfigError::NoLayers)?;
-
- let layer_config = DecoderLayerConfig {
- pre_attention_norm_config: first_layer
- .pre_attention_norm_config
- .clone()
- .unwrap_or_else(|| tf.output_norm_config.clone()),
- mixer_config: first_layer.mixer_config.clone(),
- post_attention_norm_config: first_layer.post_attention_norm_config.clone(),
- pre_mlp_norm_config: first_layer.pre_mlp_norm_config.clone(),
- mlp_config: first_layer.mlp_config.clone(),
- post_mlp_norm_config: first_layer.post_mlp_norm_config.clone(),
- };
-
- let attention_dims = Self::derive_attention_dims(tf)?;
- let num_layers = tf.num_layers.unwrap_or(tf.layer_configs.len());
-
- let sliding_window_sizes: Box<[Option<usize>]> = tf
- .layer_configs
- .iter()
- .map(|layer| layer.mixer_config.sliding_window_size())
- .collect::<Vec<_>>()
- .into_boxed_slice();
-
- let layer_types: Box<[DecoderLayerType]> = tf
- .layer_configs
- .iter()
- .map(|layer| Self::layer_type_from_mixer(&layer.mixer_config))
- .collect::<Vec<_>>()
- .into_boxed_slice();
-
- let layer_configs: Box<[DecoderLayerConfig]> = tf
- .layer_configs
- .iter()
- .map(|layer| DecoderLayerConfig {
- pre_attention_norm_config: layer
- .pre_attention_norm_config
- .clone()
- .unwrap_or_else(|| tf.output_norm_config.clone()),
- mixer_config: layer.mixer_config.clone(),
- post_attention_norm_config: layer.post_attention_norm_config.clone(),
- pre_mlp_norm_config: layer.pre_mlp_norm_config.clone(),
- mlp_config: layer.mlp_config.clone(),
- post_mlp_norm_config: layer.post_mlp_norm_config.clone(),
- })
- .collect::<Vec<_>>()
- .into_boxed_slice();
-
- Ok(DecoderConfig {
- embedding_config: self.embedding_config.clone(),
- global_rope_config: tf.global_rope_config.clone(),
- local_rope_config: tf.local_rope_config.clone(),
- layer_config,
- layer_configs: Some(layer_configs),
- output_norm_config: tf.output_norm_config.clone(),
- vocab_size: self.vocab_size,
- model_dim: tf.model_dim,
- hidden_dim: tf.hidden_dim,
- num_heads: attention_dims.num_heads,
- num_groups: attention_dims.num_groups,
- head_dim: attention_dims.head_dim,
- attention_scale: attention_dims.attention_scale,
- num_layers,
- sliding_window_sizes: Some(sliding_window_sizes),
- layer_types: Some(layer_types),
- context_length: tf.context_length,
- })
- }
-
- fn derive_attention_dims(tf: &TransformerConfig) -> Result<AttentionDims, ConfigError> {
- if let (Some(num_heads), Some(head_dim)) = (tf.num_heads, tf.head_dim) {
- return Ok(AttentionDims {
- num_heads,
- num_groups: tf.num_groups.unwrap_or(num_heads),
- head_dim,
- attention_scale: tf.attention_scale,
- });
- }
-
- if let Some(attn) = tf.layer_configs.iter().find_map(|layer| layer.mixer_config.as_attention()) {
- let num_heads = attn.num_heads.ok_or_else(|| ConfigError::MissingField("num_heads".to_string()))?;
- let head_dim = attn.head_dim.ok_or_else(|| ConfigError::MissingField("head_dim".to_string()))?;
- return Ok(AttentionDims {
- num_heads,
- num_groups: attn.num_groups.unwrap_or(num_heads),
- head_dim,
- attention_scale: attn.scale,
- });
- }
-
- if let Some(mamba) = tf.layer_configs.iter().find_map(|layer| layer.mixer_config.as_mamba()) {
- return Ok(AttentionDims {
- num_heads: mamba.num_heads,
- num_groups: mamba.num_groups,
- head_dim: mamba.head_dim,
- attention_scale: None,
- });
- }
-
- if let Some(dn) = tf.layer_configs.iter().find_map(|layer| layer.mixer_config.as_delta_net()) {
- return Ok(AttentionDims {
- num_heads: dn.num_heads,
- num_groups: dn.num_groups,
- head_dim: dn.head_dim,
- attention_scale: None,
- });
- }
-
- Ok(AttentionDims {
- num_heads: 1,
- num_groups: 1,
- head_dim: tf.model_dim,
- attention_scale: None,
- })
- }
-
- fn layer_type_from_mixer(mixer: &MixerConfig) -> DecoderLayerType {
- match mixer {
- MixerConfig::Attention(_) => DecoderLayerType::Transformer,
- MixerConfig::Mamba(config) => DecoderLayerType::StateSpace {
- conv_dim: config.conv_dim(),
- kernel_size: config.kernel_size,
- state_dim: config.state_dim,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- head_dim: config.head_dim,
- },
- MixerConfig::ShortConv(config) => DecoderLayerType::ShortConv {
- kernel_size: config.kernel_size,
- },
- MixerConfig::DeltaNet(config) => DecoderLayerType::DeltaNet {
- conv_dim: config.conv_dim(),
- kernel_size: config.kernel_size,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- head_dim: config.head_dim,
- value_head_dim: config.value_head_dim,
- },
- }
- }
-}
+use crate::config::{DecoderConfig, GenerationConfig, MessageProcessorConfig};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct LanguageModelConfig {
- pub model_config: InnerModelConfig,
+ pub model_config: DecoderConfig,
pub message_processor_config: MessageProcessorConfig,
pub generation_config: GenerationConfig,
}
-
-impl LanguageModelConfig {
- /// Get the decoder config for backward compatibility.
- /// This converts the new format to the old DecoderConfig format.
- pub fn decoder_config(&self) -> Result<DecoderConfig, ConfigError> {
- self.model_config.to_decoder_config()
- }
-}
diff --git a/crates/backend-uzu/src/config/linear.rs b/crates/backend-uzu/src/config/linear.rs
index 0456dfa34..d522970b4 100644
--- a/crates/backend-uzu/src/config/linear.rs
+++ b/crates/backend-uzu/src/config/linear.rs
@@ -54,7 +54,3 @@ impl LinearConfig {
}
}
}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/linear_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/mamba.rs b/crates/backend-uzu/src/config/mamba.rs
index aaa0a8cd3..ce2f81e0f 100644
--- a/crates/backend-uzu/src/config/mamba.rs
+++ b/crates/backend-uzu/src/config/mamba.rs
@@ -1,19 +1,13 @@
use serde::{Deserialize, Serialize};
-use super::{common::ConfigDataType, linear::LinearConfig};
+use super::{linear::LinearConfig, short_conv::SeparableCausalConvConfig};
use crate::backends::common::ActivationConfig;
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct CausalConv1dConfig {
- pub precision: ConfigDataType,
- pub has_biases: bool,
-}
-
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Mamba2Config {
pub in_projection_config: LinearConfig,
pub out_projection_config: LinearConfig,
- pub conv_config: CausalConv1dConfig,
+ pub conv_config: SeparableCausalConvConfig,
pub activation: ActivationConfig,
pub kernel_size: usize,
pub num_heads: usize,
@@ -23,6 +17,7 @@ pub struct Mamba2Config {
pub expansion_factor: usize,
pub has_in_biases: bool,
pub has_out_biases: bool,
+ pub chunk_size: usize,
}
impl Mamba2Config {
diff --git a/crates/backend-uzu/src/config/message_processor.rs b/crates/backend-uzu/src/config/message_processor.rs
index 1c3064f80..fe1bd6935 100644
--- a/crates/backend-uzu/src/config/message_processor.rs
+++ b/crates/backend-uzu/src/config/message_processor.rs
@@ -7,5 +7,7 @@ pub struct MessageProcessorConfig {
pub system_role_name: String,
pub user_role_name: String,
pub assistant_role_name: String,
+ pub eos_token: Option<String>,
pub bos_token: Option<String>,
+ pub default_system_prompt: Option<String>,
}
diff --git a/crates/backend-uzu/src/config/metadata.rs b/crates/backend-uzu/src/config/metadata.rs
index 9525c8da0..43389e564 100644
--- a/crates/backend-uzu/src/config/metadata.rs
+++ b/crates/backend-uzu/src/config/metadata.rs
@@ -1,22 +1,19 @@
use serde::{Deserialize, Serialize};
-use super::{ModelConfig, ModelType};
-
-fn default_model_type() -> ModelType {
- ModelType::LanguageModel
-}
+use super::ModelType;
+use crate::backends::common::gpu_types::QuantizationMode;
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct ModelMetadata {
+pub struct ModelMetadata<T> {
pub toolchain_version: String,
pub vendor: String,
pub family: String,
pub name: String,
pub size: String,
- pub quantization: Option<String>,
+ pub quantization: Option<QuantizationMode>,
pub repo: String,
pub use_cases: Vec<String>,
- #[serde(default = "default_model_type")]
pub model_type: ModelType,
- pub model_config: ModelConfig,
+ pub model_config: T,
+ pub grammar_start_tokens: Vec<String>,
}
diff --git a/crates/backend-uzu/src/config/mixer.rs b/crates/backend-uzu/src/config/mixer.rs
new file mode 100644
index 000000000..dc26bf3b3
--- /dev/null
+++ b/crates/backend-uzu/src/config/mixer.rs
@@ -0,0 +1,55 @@
+use serde::{Deserialize, Serialize};
+
+use super::{AttentionConfig, ConfigDataType, DeltaNetAttentionConfig, Mamba2Config, ShortConvConfig};
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+#[serde(tag = "type")]
+pub enum MixerConfig {
+ #[serde(rename = "AttentionConfig")]
+ Attention(AttentionConfig),
+ #[serde(rename = "Mamba2Config")]
+ Mamba(Mamba2Config),
+ #[serde(rename = "ShortConvConfig")]
+ ShortConv(ShortConvConfig),
+ #[serde(rename = "DeltaNetAttentionConfig")]
+ DeltaNet(DeltaNetAttentionConfig),
+}
+
+impl MixerConfig {
+ pub fn as_attention(&self) -> Option<&AttentionConfig> {
+ match self {
+ MixerConfig::Attention(config) => Some(config),
+ _ => None,
+ }
+ }
+
+ pub fn as_short_conv(&self) -> Option<&ShortConvConfig> {
+ match self {
+ MixerConfig::ShortConv(config) => Some(config),
+ _ => None,
+ }
+ }
+
+ pub fn as_delta_net(&self) -> Option<&DeltaNetAttentionConfig> {
+ match self {
+ MixerConfig::DeltaNet(config) => Some(config),
+ _ => None,
+ }
+ }
+
+ pub fn sliding_window_size(&self) -> Option<usize> {
+ match self {
+ MixerConfig::Attention(config) => config.sliding_window_size,
+ MixerConfig::Mamba(_) | MixerConfig::ShortConv(_) | MixerConfig::DeltaNet(_) => None,
+ }
+ }
+
+ pub fn activation_precision(&self) -> ConfigDataType {
+ match self {
+ MixerConfig::Attention(c) => c.qkv_projection_config.activation_precision(),
+ MixerConfig::Mamba(c) => c.in_projection_config.activation_precision(),
+ MixerConfig::ShortConv(c) => c.in_projection_config.activation_precision(),
+ MixerConfig::DeltaNet(c) => c.in_proj_config.activation_precision(),
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/config/mlp.rs b/crates/backend-uzu/src/config/mlp.rs
index ec24b6a56..40e2f7ada 100644
--- a/crates/backend-uzu/src/config/mlp.rs
+++ b/crates/backend-uzu/src/config/mlp.rs
@@ -15,30 +15,23 @@ pub enum MLPConfig {
pub struct DenseMLPConfig {
pub linear_config: LinearConfig,
pub activation: ActivationConfig,
- #[serde(default)]
pub has_up_biases: bool,
- #[serde(default)]
pub has_down_biases: bool,
- #[serde(default)]
- pub gate_clipping: Option<[Option<f32>; 2]>,
- #[serde(default)]
- pub up_clipping: Option<[Option<f32>; 2]>,
- #[serde(default = "default_activation_to_gate")]
- pub activation_to_gate: bool,
-}
-
-fn default_activation_to_gate() -> bool {
- true
+ pub gate_clipping: Option<(Option<f32>, Option<f32>)>,
+ pub up_clipping: Option<(Option<f32>, Option<f32>)>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct MixtureOfExpertsConfig {
+ pub expert_config: DenseMLPConfig,
+ pub router_config: LinearConfig,
+ pub routing_function: RoutingFunctionConfig,
pub num_routed_experts: usize,
pub num_active_routed_experts: usize,
- pub routing_function: RoutingFunctionConfig,
- pub router_config: LinearConfig,
pub router_has_biases: bool,
- pub expert_config: MoeExpertConfig,
+ pub num_shared_experts: usize,
+ pub expert_hidden_dim: usize,
+ pub gate_config: Option<LinearConfig>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
@@ -47,17 +40,3 @@ pub enum RoutingFunctionConfig {
#[serde(rename = "SoftmaxRouting")]
SoftmaxRouting,
}
-
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct MoeExpertConfig {
- pub linear_config: LinearConfig,
- pub activation: ActivationConfig,
- pub has_up_biases: bool,
- pub has_down_biases: bool,
- pub gate_clipping: [Option<f32>; 2],
- pub up_clipping: [f32; 2],
-}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/mlp_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/mod.rs b/crates/backend-uzu/src/config/mod.rs
index acc0aaa7a..399b09cd3 100644
--- a/crates/backend-uzu/src/config/mod.rs
+++ b/crates/backend-uzu/src/config/mod.rs
@@ -3,24 +3,23 @@ mod classifier;
mod classifier_model;
mod common;
mod decoder;
-mod decoder_layer;
mod delta_net;
mod embedding;
-mod error;
mod generation;
mod language_model;
mod linear;
mod mamba;
mod message_processor;
mod metadata;
+mod mixer;
mod mlp;
-mod model_config;
mod model_type;
mod normalization;
mod rope;
mod short_conv;
mod transformer;
mod transformer_layer;
+#[cfg(metal_backend)]
mod tts_model;
pub use attention::*;
@@ -28,22 +27,21 @@ pub use classifier::*;
pub use classifier_model::*;
pub use common::*;
pub use decoder::*;
-pub use decoder_layer::*;
pub use delta_net::*;
pub use embedding::*;
-pub use error::*;
pub use generation::*;
pub use language_model::*;
pub use linear::*;
pub use mamba::*;
pub use message_processor::*;
pub use metadata::*;
+pub use mixer::*;
pub use mlp::*;
-pub use model_config::*;
pub use model_type::*;
pub use normalization::*;
pub use rope::*;
pub use short_conv::*;
pub use transformer::*;
pub use transformer_layer::*;
+#[cfg(metal_backend)]
pub use tts_model::*;
diff --git a/crates/backend-uzu/src/config/model_config.rs b/crates/backend-uzu/src/config/model_config.rs
deleted file mode 100644
index 51673d313..000000000
--- a/crates/backend-uzu/src/config/model_config.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-use super::{ClassifierModelConfig, LanguageModelConfig, TtsModelConfig};
-
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-#[serde(untagged)]
-pub enum ModelConfig {
- LanguageModel(LanguageModelConfig),
- Classifier(ClassifierModelConfig),
- Tts(TtsModelConfig),
-}
-
-impl ModelConfig {
- pub fn as_language_model(&self) -> Option<&LanguageModelConfig> {
- match self {
- ModelConfig::LanguageModel(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn as_classifier(&self) -> Option<&ClassifierModelConfig> {
- match self {
- ModelConfig::Classifier(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn as_tts(&self) -> Option<&TtsModelConfig> {
- match self {
- ModelConfig::Tts(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn is_language_model(&self) -> bool {
- matches!(self, ModelConfig::LanguageModel(_))
- }
-
- pub fn is_classifier(&self) -> bool {
- matches!(self, ModelConfig::Classifier(_))
- }
-
- pub fn is_tts(&self) -> bool {
- matches!(self, ModelConfig::Tts(_))
- }
-}
diff --git a/crates/backend-uzu/src/config/normalization/normalization_config.rs b/crates/backend-uzu/src/config/normalization/normalization_config.rs
index 17dac6b7b..262a800b2 100644
--- a/crates/backend-uzu/src/config/normalization/normalization_config.rs
+++ b/crates/backend-uzu/src/config/normalization/normalization_config.rs
@@ -10,12 +10,6 @@ pub struct NormalizationConfig {
pub epsilon: f32,
pub scale_offset: Option<f32>,
pub upcast_mode: UpcastMode,
- #[serde(default)]
pub subtract_mean: bool,
- #[serde(default)]
pub use_bias: bool,
}
-
-#[cfg(test)]
-#[path = "../../../tests/unit/config/normalization/normalization_config_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/rope.rs b/crates/backend-uzu/src/config/rope.rs
index 8e9754fb3..3300cb497 100644
--- a/crates/backend-uzu/src/config/rope.rs
+++ b/crates/backend-uzu/src/config/rope.rs
@@ -33,7 +33,8 @@ pub enum RoPEConfig {
beta_slow: f32,
truncate: bool,
},
- LinearScalingRoPEConfig {
+ #[serde(rename = "LinearScalingRoPEConfig")]
+ LinearScaling {
#[serde(flatten)]
common: RopeConfigCommon,
scaling_factor: f32,
@@ -43,7 +44,7 @@ pub enum RoPEConfig {
impl RoPEConfig {
pub fn common(&self) -> &RopeConfigCommon {
match self {
- RoPEConfig::Unscaled(config) => &config,
+ RoPEConfig::Unscaled(config) => config,
RoPEConfig::Llama {
common,
..
@@ -52,14 +53,10 @@ impl RoPEConfig {
common,
..
} => common,
- RoPEConfig::LinearScalingRoPEConfig {
+ RoPEConfig::LinearScaling {
common,
..
} => common,
}
}
}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/rope_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/transformer.rs b/crates/backend-uzu/src/config/transformer.rs
index 9e6040854..343e78958 100644
--- a/crates/backend-uzu/src/config/transformer.rs
+++ b/crates/backend-uzu/src/config/transformer.rs
@@ -8,18 +8,7 @@ pub struct TransformerConfig {
pub local_rope_config: Option<RoPEConfig>,
pub layer_configs: Vec<TransformerLayerConfig>,
pub output_norm_config: NormalizationConfig,
-
pub model_dim: usize,
pub hidden_dim: usize,
- #[serde(default)]
- pub num_heads: Option<usize>,
- #[serde(default)]
- pub num_groups: Option<usize>,
- #[serde(default)]
- pub head_dim: Option<usize>,
- #[serde(default)]
- pub attention_scale: Option<f32>,
- #[serde(default)]
- pub num_layers: Option<usize>,
pub context_length: usize,
}
diff --git a/crates/backend-uzu/src/config/transformer_layer.rs b/crates/backend-uzu/src/config/transformer_layer.rs
index 462e22ba9..b297b5a2c 100644
--- a/crates/backend-uzu/src/config/transformer_layer.rs
+++ b/crates/backend-uzu/src/config/transformer_layer.rs
@@ -1,25 +1,13 @@
use serde::{Deserialize, Serialize};
-use super::{AttentionConfig, MLPConfig, MixerConfig, NormalizationConfig};
+use super::{MLPConfig, MixerConfig, NormalizationConfig};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct TransformerLayerConfig {
- #[serde(alias = "pre_mixer_norm_config")]
- pub pre_attention_norm_config: Option<NormalizationConfig>,
+ pub pre_mixer_norm_config: Option<NormalizationConfig>,
pub mixer_config: MixerConfig,
- #[serde(alias = "post_mixer_norm_config")]
- pub post_attention_norm_config: Option<NormalizationConfig>,
+ pub post_mixer_norm_config: Option<NormalizationConfig>,
pub pre_mlp_norm_config: NormalizationConfig,
pub mlp_config: MLPConfig,
pub post_mlp_norm_config: Option<NormalizationConfig>,
}
-
-impl TransformerLayerConfig {
- pub fn attention_config(&self) -> Option<&AttentionConfig> {
- self.mixer_config.as_attention()
- }
-}
-
-#[cfg(test)]
-#[path = "../../tests/unit/config/transformer_layer_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/config/tts_model.rs b/crates/backend-uzu/src/config/tts_model.rs
index d6f7cdcff..a60ab6ee6 100644
--- a/crates/backend-uzu/src/config/tts_model.rs
+++ b/crates/backend-uzu/src/config/tts_model.rs
@@ -276,276 +276,3 @@ impl TtsModelConfig {
crate::audio::AudioGenerationContext::from_tts_config_and_model_path(&self.tts_config, model_path)
}
}
-
-#[cfg(test)]
-mod tests {
- use crate::config::{ModelConfig, ModelMetadata, ModelType};
-
- fn descript_audio_decoder_config_json() -> serde_json::Value {
- serde_json::json!({
- "precision": "float16",
- "conv_config": {
- "precision": "float16",
- "has_biases": true
- },
- "snake_config": {
- "precision": "float16"
- },
- "decoder_block_config": {
- "precision": "float16",
- "snake_config": {
- "precision": "float16"
- },
- "trans_conv_config": {
- "precision": "float16",
- "has_biases": true
- },
- "res_unit_config": {
- "precision": "float16",
- "snake_config": {
- "precision": "float16"
- },
- "conv_config": {
- "precision": "float16",
- "has_biases": true
- },
- "causal": true
- },
- "causal": true
- },
- "causal": true
- })
- }
-
- fn fishaudio_text_decoder_config_json() -> serde_json::Value {
- let norm_config = serde_json::json!({
- "scale_precision": "float32",
- "accumulation_precision": "float32",
- "epsilon": 1e-5,
- "scale_offset": null,
- "upcast_mode": "full_layer",
- "subtract_mean": true
- });
- let transformer_config = serde_json::json!({
- "global_rope_config": null,
- "local_rope_config": null,
- "layer_configs": [],
- "output_norm_config": norm_config,
- "model_dim": 256,
- "hidden_dim": 256,
- "context_length": 512
- });
- serde_json::json!({
- "type": "FishAudioTextDecoderConfig",
- "slow_embeddings_config": { "precision": "float16", "input_scale": null, "logit_soft_cap": null },
- "slow_model_config": transformer_config,
- "slow_readout_config": { "precision": "float16" },
- "fast_embeddings_config": { "precision": "float16", "input_scale": null, "logit_soft_cap": null },
- "fast_model_config": transformer_config,
- "fast_readout_config": { "precision": "float16" },
- "codebook_embeddings_config": { "precision": "float16", "input_scale": null, "logit_soft_cap": null },
- "fast_model_projection_config": null,
- "semantic_token_begin_id": 100,
- "semantic_token_end_id": 1123,
- "im_end_token_id": 4,
- "codebook_size": 1024,
- "vocab_size": 2048,
- "slow_model_dim": 256,
- "fast_model_dim": 256,
- "num_codebooks": 8,
- "max_seq_len": 4096,
- "scale_codebook_embeddings": false,
- "short_logits_size": 1124,
- "repeat_window_size": 16
- })
- }
-
- #[test]
- fn metadata_with_tts_model_type_parses() {
- let config_json = serde_json::json!({
- "toolchain_version": "0.0.0-test",
- "vendor": "NVIDIA",
- "family": "nanocodec",
- "name": "nemo-nano-codec-22khz-1.78kbps-12.5fps",
- "size": "0.1B",
- "quantization": null,
- "repo": "nvidia/nemo-nano-codec-22khz-1.78kbps-12.5fps",
- "use_cases": [],
- "model_type": "tts_model",
- "model_config": {
- "tts_config": {
- "text_decoder_config": fishaudio_text_decoder_config_json(),
- "audio_decoder_config": {
- "type": "DescriptAudioCodecConfig",
- "precision": "float16",
- "samplerate": 44100,
- "encoder_dim": 1024,
- "encoder_rates": [2, 4, 8, 8],
- "decoder_dim": 1536,
- "n_codebooks": 9,
- "codebook_dim": 8,
- "codebook_size": 1024,
- "semantic_codebook_size": 4096,
- "input_dim": 1024,
- "downsample_factor": [2, 2],
- "decoder_rates": [8, 8, 4, 2],
- "decoder_config": descript_audio_decoder_config_json(),
- "quantizer_config": {
- "post_module_config": {
- "global_rope_config": null,
- "local_rope_config": null,
- "layer_configs": [],
- "output_norm_config": {
- "scale_precision": "float32",
- "accumulation_precision": "float32",
- "epsilon": 1e-5,
- "scale_offset": null,
- "upcast_mode": "full_layer",
- "subtract_mean": true
- },
- "model_dim": 1024,
- "hidden_dim": 1024,
- "context_length": 1
- },
- "upsampler_config": {
- "block_configs": []
- }
- }
- },
- },
- "message_processor_config": {
- "prompt_template": "{% for message in messages %}{{message.content}}{% endfor %}",
- "drop_initial_newline": true
- }
- }
- });
-
- let metadata: ModelMetadata = serde_json::from_value(config_json).expect("metadata parse");
- assert_eq!(metadata.model_type, ModelType::TtsModel);
-
- let tts_config = metadata.model_config.as_tts().expect("tts config");
- assert_eq!(
- tts_config.message_processor_config.prompt_template,
- "{% for message in messages %}{{message.content}}{% endfor %}"
- );
- assert!(tts_config.message_processor_config.drop_initial_newline);
- assert!(tts_config.message_processor_config.default_message_fields.is_empty());
- }
-
- #[test]
- fn tts_model_config_helpers_work() {
- let model_config_json = serde_json::json!({
- "tts_config": {
- "text_decoder_config": fishaudio_text_decoder_config_json(),
- "audio_decoder_config": {
- "type": "DescriptAudioCodecConfig",
- "precision": "float16",
- "samplerate": 44100,
- "encoder_dim": 1024,
- "encoder_rates": [2, 4, 8, 8],
- "decoder_dim": 1536,
- "n_codebooks": 9,
- "codebook_dim": 8,
- "codebook_size": 1024,
- "semantic_codebook_size": 4096,
- "input_dim": 1024,
- "downsample_factor": [2, 2],
- "decoder_rates": [8, 8, 4, 2],
- "decoder_config": descript_audio_decoder_config_json(),
- "quantizer_config": {
- "post_module_config": {
- "global_rope_config": null,
- "local_rope_config": null,
- "layer_configs": [],
- "output_norm_config": {
- "scale_precision": "float32",
- "accumulation_precision": "float32",
- "epsilon": 1e-5,
- "scale_offset": null,
- "upcast_mode": "full_layer",
- "subtract_mean": true
- },
- "model_dim": 1024,
- "hidden_dim": 1024,
- "context_length": 1
- },
- "upsampler_config": {
- "block_configs": []
- }
- }
- },
- },
- "message_processor_config": {
- "prompt_template": "{{messages[0].content}}"
- }
- });
-
- let model_config: ModelConfig = serde_json::from_value(model_config_json).expect("model config parse");
- assert!(model_config.is_tts());
- assert!(model_config.as_tts().is_some());
- assert!(!model_config.is_classifier());
- assert!(!model_config.is_language_model());
-
- let tts = model_config.as_tts().expect("tts variant");
- assert_eq!(tts.message_processor_config.prompt_template, "{{messages[0].content}}");
- assert!(tts.message_processor_config.drop_initial_newline);
- assert!(tts.message_processor_config.default_message_fields.is_empty());
- }
-
- #[test]
- fn tts_model_config_rejects_untyped_decoder_config() {
- let model_config_json = serde_json::json!({
- "tts_config": {
- "text_decoder_config": fishaudio_text_decoder_config_json(),
- "audio_decoder_config": {
- "type": "DescriptAudioCodecConfig",
- "precision": "float16",
- "samplerate": 44100,
- "encoder_dim": 1024,
- "encoder_rates": [2, 4, 8, 8],
- "decoder_dim": 1536,
- "n_codebooks": 9,
- "codebook_dim": 8,
- "codebook_size": 1024,
- "semantic_codebook_size": 4096,
- "input_dim": 1024,
- "downsample_factor": [2, 2],
- "decoder_rates": [8, 8, 4, 2],
- "decoder_config": {},
- "quantizer_config": {
- "post_module_config": {
- "global_rope_config": null,
- "local_rope_config": null,
- "layer_configs": [],
- "output_norm_config": {
- "scale_precision": "float32",
- "accumulation_precision": "float32",
- "epsilon": 1e-5,
- "scale_offset": null,
- "upcast_mode": "full_layer",
- "subtract_mean": true
- },
- "model_dim": 1024,
- "hidden_dim": 1024,
- "context_length": 1
- },
- "upsampler_config": {
- "block_configs": []
- }
- }
- },
- },
- "message_processor_config": {
- "prompt_template": "{{messages[0].content}}"
- }
- });
-
- let error =
- serde_json::from_value::<ModelConfig>(model_config_json).expect_err("decoder_config should be typed");
- let error_text = error.to_string();
- assert!(
- error_text.contains("did not match any variant") || error_text.contains("conv_config"),
- "unexpected error: {error}"
- );
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/attention.rs b/crates/backend-uzu/src/encodable_block/attention.rs
index a402b1099..c6906f248 100644
--- a/crates/backend-uzu/src/encodable_block/attention.rs
+++ b/crates/backend-uzu/src/encodable_block/attention.rs
@@ -16,6 +16,7 @@ use crate::{
attention::{AttentionGemmArguments, AttentionGemmBlock},
},
},
+ config::AttentionConfig,
forward_pass::kv_cache_layer::{KVCacheLayer, KVCacheLayerState},
};
@@ -50,7 +51,6 @@ pub struct Attention<B: Backend> {
}
pub struct AttentionArguments<'a, B: Backend> {
- pub projection_step: usize,
pub token_subtrie_ranges: Option<&'a Allocation<B>>,
pub attention_sinks: Option<&'a Allocation<B>>,
pub kv_cache_layer: Option<&'a mut KVCacheLayer<B>>,
@@ -60,10 +60,7 @@ impl<B: Backend> Attention<B> {
pub fn new(
context: &B::Context,
data_type: DataType,
- attention_scale: Option<f32>,
- has_sinks: bool,
- is_causal: bool,
- sliding_window_size: Option<usize>,
+ config: &AttentionConfig,
has_gate: bool,
) -> Result<Self, B::Error> {
let mut single_pass_kernels = HashMap::new();
@@ -81,11 +78,11 @@ impl<B: Backend> Attention<B> {
context,
data_type,
head_dim,
- has_sinks,
+ config.has_sinks,
is_kv_cache_ring,
- is_causal,
+ config.is_causal,
is_trie,
- sliding_window_size.is_some(),
+ config.sliding_window_size.is_some(),
)?;
single_pass_kernels.insert(key, sp_kernel);
@@ -93,11 +90,11 @@ impl<B: Backend> Attention<B> {
context,
data_type,
head_dim,
- has_sinks,
+ config.has_sinks,
is_kv_cache_ring,
- is_causal,
+ config.is_causal,
is_trie,
- sliding_window_size.is_some(),
+ config.sliding_window_size.is_some(),
)?;
two_pass_1_kernels.insert(key, tp1_kernel);
@@ -125,9 +122,9 @@ impl<B: Backend> Attention<B> {
gate_kernel,
gemm_block,
data_type,
- attention_scale,
- is_causal,
- sliding_window_size,
+ attention_scale: config.scale,
+ is_causal: config.is_causal,
+ sliding_window_size: config.sliding_window_size,
})
}
@@ -184,15 +181,15 @@ impl<B: Backend> Attention<B> {
ring_length,
window_length,
} => {
- let overflow = (ring_length + args.projection_step).saturating_sub(window_length);
+ let overflow = ring_length.saturating_sub(window_length);
Some(RingParams {
ring_offset: ((ring_offset + overflow) % window_length) as u32,
- ring_length: (ring_length + args.projection_step).min(window_length) as u32,
+ ring_length: ring_length.min(window_length) as u32,
})
},
_ => None,
};
- (max_sequence_length, layer.projected_segment_prefix_length(args.projection_step), ring_params)
+ (max_sequence_length, layer.prefix_segment_length(), ring_params)
} else {
(suffix_length, 0, None)
};
diff --git a/crates/backend-uzu/src/encodable_block/classifier_layer.rs b/crates/backend-uzu/src/encodable_block/classifier_layer.rs
index e260cf96b..b0a4ca4aa 100644
--- a/crates/backend-uzu/src/encodable_block/classifier_layer.rs
+++ b/crates/backend-uzu/src/encodable_block/classifier_layer.rs
@@ -3,10 +3,8 @@ use std::rc::Rc;
use crate::{
DataType,
backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder, Kernels, kernel::TensorAddSwapKernel},
- config::TransformerLayerConfig,
- encodable_block::{
- Attention, AttentionArguments, EncodingParameters, LayerArguments, Linear, Mlp, Normalization, QKNorm, Rope,
- },
+ config::{TransformerConfig, TransformerLayerConfig},
+ encodable_block::{Attention, AttentionArguments, LayerArguments, Linear, Mlp, Normalization, QKNorm, Rope},
forward_pass::state::RopeType,
parameters::ParameterTree,
};
@@ -33,59 +31,49 @@ pub struct ClassifierLayer<B: Backend> {
impl<B: Backend> ClassifierLayer<B> {
pub fn new(
- context: Rc<B::Context>,
+ context: &B::Context,
+ transformer_config: &TransformerConfig,
layer_config: &TransformerLayerConfig,
layer_index: usize,
- model_dim: usize,
- hidden_dim: usize,
- num_heads: usize,
- head_dim: usize,
- num_groups: usize,
- attention_scale: Option<f32>,
layer_loader: &ParameterTree<B::Context>,
rope: Rc<Rope<B>>,
) -> Self {
- let ctx = context.as_ref(); // Reference for functions expecting &B::Context
let attention_config = layer_config.mixer_config.as_attention().expect("Classifier layers must use attention");
let intermediate_data_type: DataType = attention_config.qkv_projection_config.activation_precision().into();
- let pre_attention_norm = if let Some(norm_config) = &layer_config.pre_attention_norm_config {
- if layer_loader.subtree("pre_mixer_norm").is_ok() {
- Some(
- Normalization::new(
- ctx,
- intermediate_data_type,
- norm_config.clone(),
- &layer_loader.subtree("pre_mixer_norm").unwrap(),
- )
- .expect("Failed to create pre-attention norm kernel"),
- )
- } else {
- None
- }
- } else {
- None
- };
+ let pre_attention_norm = layer_config.pre_mixer_norm_config.as_ref().map(|norm_config| {
+ Normalization::new(
+ context,
+ intermediate_data_type,
+ norm_config.clone(),
+ &layer_loader.subtree("pre_mixer_norm").unwrap(),
+ )
+ .expect("Failed to create pre-attention norm kernel")
+ });
let qkv_projection = <dyn Linear<B>>::new(
&attention_config.qkv_projection_config,
- model_dim,
- [num_heads * head_dim, num_groups * head_dim, num_groups * head_dim],
- ctx,
+ transformer_config.model_dim,
+ [
+ attention_config.num_heads * attention_config.head_dim,
+ attention_config.num_groups * attention_config.head_dim,
+ attention_config.num_groups * attention_config.head_dim,
+ ],
+ context,
&layer_loader.subtree("mixer.qkv_projection").unwrap(),
)
.expect("Failed to create qkv projection");
let qk_norm = if attention_config.query_norm_config.is_some() || attention_config.key_norm_config.is_some() {
match QKNorm::new(
- ctx,
+ context,
intermediate_data_type,
attention_config.query_norm_config.clone(),
attention_config.key_norm_config.clone(),
&layer_loader.subtree("mixer").unwrap(),
- num_heads,
- num_groups,
- head_dim,
+ attention_config.num_heads,
+ attention_config.num_groups,
+ attention_config.head_dim,
) {
Ok(norm) => Some(norm),
Err(e) => panic!("Failed to create QK norm kernel for layer {}: {:?}", layer_index, e),
@@ -96,32 +84,28 @@ impl<B: Backend> ClassifierLayer<B> {
let out_projection = <dyn Linear<B>>::new(
&attention_config.out_projection_config,
- num_heads * head_dim,
- [model_dim],
- ctx,
+ attention_config.num_heads * attention_config.head_dim,
+ [transformer_config.model_dim],
+ context,
&layer_loader.subtree("mixer.out_projection").unwrap(),
)
.expect("Failed to create out projection");
- let post_attention_norm = if let Some(norm_config) = &layer_config.post_attention_norm_config {
- Some(
- Normalization::new(
- ctx,
- intermediate_data_type,
- norm_config.clone(),
- &layer_loader.subtree("post_mixer_norm").unwrap(),
- )
- .expect("Failed to create post-attention norm kernel"),
+ let post_attention_norm = layer_config.post_mixer_norm_config.as_ref().map(|norm_config| {
+ Normalization::new(
+ context,
+ intermediate_data_type,
+ norm_config.clone(),
+ &layer_loader.subtree("post_mixer_norm").unwrap(),
)
- } else {
- None
- };
+ .expect("Failed to create post-attention norm kernel")
+ });
- let mixer_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(ctx, intermediate_data_type)
+ let mixer_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(context, intermediate_data_type)
.expect("Failed to create mixer residual add kernel");
let pre_mlp_norm = Normalization::new(
- ctx,
+ context,
intermediate_data_type,
layer_config.pre_mlp_norm_config.clone(),
&layer_loader.subtree("pre_mlp_norm").unwrap(),
@@ -130,41 +114,29 @@ impl<B: Backend> ClassifierLayer<B> {
let (mlp, mlp_hadamard_factors) = <dyn Mlp<B>>::new(
&layer_config.mlp_config,
- model_dim,
- hidden_dim,
- context.as_ref(),
+ transformer_config.model_dim,
+ transformer_config.hidden_dim,
+ context,
&layer_loader.subtree("mlp").unwrap(),
)
.expect("Failed to create mlp block");
assert!(mlp_hadamard_factors.is_none(), "classifier doesn't support hadamard");
- let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
- Some(
- Normalization::new(
- ctx,
- intermediate_data_type,
- norm_config.clone(),
- &layer_loader.subtree("post_mlp_norm").unwrap(),
- )
- .expect("Failed to create post-MLP norm kernel"),
+ let post_mlp_norm = layer_config.post_mlp_norm_config.as_ref().map(|norm_config| {
+ Normalization::new(
+ context,
+ intermediate_data_type,
+ norm_config.clone(),
+ &layer_loader.subtree("post_mlp_norm").unwrap(),
)
- } else {
- None
- };
+ .expect("Failed to create post-MLP norm kernel")
+ });
- let attention = Attention::new(
- ctx,
- intermediate_data_type,
- attention_scale,
- attention_config.has_sinks,
- false,
- attention_config.sliding_window_size,
- false,
- )
- .expect("Failed to create attention kernel");
+ let attention = Attention::new(context, intermediate_data_type, attention_config, false)
+ .expect("Failed to create attention kernel");
- let mlp_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(ctx, intermediate_data_type)
+ let mlp_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(context, intermediate_data_type)
.expect("Failed to create mlp residual add kernel");
Self {
@@ -181,17 +153,16 @@ impl<B: Backend> ClassifierLayer<B> {
mlp,
post_mlp_norm,
mlp_residual_add,
- model_dim,
- num_heads,
- num_groups,
- head_dim,
+ model_dim: transformer_config.model_dim,
+ num_heads: attention_config.num_heads,
+ num_groups: attention_config.num_groups,
+ head_dim: attention_config.head_dim,
}
}
pub fn encode(
&self,
args: LayerArguments<B>,
- parameters: &EncodingParameters,
main: Allocation<B>,
shortcut: &mut Allocation<B>,
encoder: &mut Encoder<B>,
@@ -253,7 +224,6 @@ impl<B: Backend> ClassifierLayer<B> {
)?;
let attention_output = self.attention.encode(
AttentionArguments {
- projection_step: parameters.projection_step.unwrap_or(0),
token_subtrie_ranges,
attention_sinks,
kv_cache_layer: None,
diff --git a/crates/backend-uzu/src/encodable_block/decoder.rs b/crates/backend-uzu/src/encodable_block/decoder.rs
index e3d8f1948..9cb19bf21 100644
--- a/crates/backend-uzu/src/encodable_block/decoder.rs
+++ b/crates/backend-uzu/src/encodable_block/decoder.rs
@@ -9,13 +9,10 @@ use crate::forward_pass::traces::ActivationTrace;
use crate::{
DataType,
backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder},
- config::{DecoderConfig, DecoderLayerType, MixerConfig},
- encodable_block::{
- Embedding, EncodingParameters, LayerArguments, LayerExecutables, RMSNorm, Rope, embedding::EmbeddingError,
- },
+ config::DecoderConfig,
+ encodable_block::{Embedding, LayerArguments, LayerExecutables, RMSNorm, Rope, embedding::EmbeddingError},
forward_pass::{
cache_layers::CacheLayers,
- model_shape::ModelShape,
state::{RopeType, SharedBuffers},
},
parameters::ParameterTree,
@@ -68,7 +65,7 @@ impl<B: Backend> Decoder<B> {
let embed = Embedding::new(
context,
decoder_config.vocab_size as u32,
- decoder_config.model_dim as u32,
+ decoder_config.transformer_config.model_dim as u32,
&decoder_config.embedding_config,
&embedding_weight_loader,
)
@@ -101,7 +98,7 @@ impl<B: Backend> Decoder<B> {
let embed = Embedding::new_with_lookup_and_readout_trees(
context,
decoder_config.vocab_size as u32,
- decoder_config.model_dim as u32,
+ decoder_config.transformer_config.model_dim as u32,
&decoder_config.embedding_config,
&embedding_weight_loader,
&readout_weight_loader,
@@ -127,89 +124,37 @@ impl<B: Backend> Decoder<B> {
let decoder_weight_loader =
root_weight_loader.subtree(transformer_subtree).expect("transformer subtree not found");
- let attention_data_type = Self::attention_data_type(&decoder_config);
- let norm_reference_layer =
- decoder_config.layer_configs.as_ref().map(|configs| &configs[0]).unwrap_or(&decoder_config.layer_config);
- let norm_data_type: DataType = match &norm_reference_layer.mixer_config {
- MixerConfig::Attention(attention_config) => {
- attention_config.qkv_projection_config.activation_precision().into()
- },
- MixerConfig::Mamba(mamba_config) => mamba_config.in_projection_config.activation_precision().into(),
- MixerConfig::ShortConv(short_conv_config) => {
- short_conv_config.in_projection_config.activation_precision().into()
- },
- MixerConfig::DeltaNet(config) => config.in_proj_config.activation_precision().into(),
- };
-
- let global_rope = if decoder_config.global_rope_config.is_some() {
- attention_data_type
- .as_ref()
- .map(|data_type| Self::create_rope_block(&context, *data_type, RopeType::Global))
- } else {
- None
- };
-
- let local_rope = if decoder_config.local_rope_config.is_some() {
- attention_data_type.as_ref().map(|data_type| Self::create_rope_block(&context, *data_type, RopeType::Local))
- } else {
- None
- };
-
- let model_shape = ModelShape::from_decoder_config(&decoder_config);
- let sliding_window_sizes = model_shape.sliding_window_length_per_layer.clone();
-
- let layers = (0..decoder_config.num_layers)
- .map(|layer_index| {
- let layer_config = decoder_config
- .layer_configs
- .as_ref()
- .map(|configs| &configs[layer_index])
- .unwrap_or(&decoder_config.layer_config);
- let layer_type = model_shape.layer_type(layer_index);
- let rope_for_layer = match layer_type {
- DecoderLayerType::Transformer => {
- if let Some(_) = sliding_window_sizes[layer_index]
- && let Some(local_rope_block) = local_rope.clone()
- {
- Some(local_rope_block)
- } else {
- Some(global_rope.clone().expect("Global rope missing for transformer layer"))
- }
- },
- DecoderLayerType::StateSpace {
- ..
- } => None,
- DecoderLayerType::ShortConv {
- ..
- } => None,
- DecoderLayerType::DeltaNet {
- ..
- } => None,
- };
+ let tf = &decoder_config.transformer_config;
+ let norm_data_type: DataType = tf.layer_configs[0].mixer_config.activation_precision().into();
+
+ let global_rope =
+ tf.global_rope_config.is_some().then(|| Self::create_rope_block(context, norm_data_type, RopeType::Global));
+ let local_rope =
+ tf.local_rope_config.is_some().then(|| Self::create_rope_block(context, norm_data_type, RopeType::Local));
+
+ let layers = tf
+ .layer_configs
+ .iter()
+ .enumerate()
+ .map(|(layer_index, layer_config)| {
+ let rope_for_layer = layer_config.mixer_config.as_attention().map(|attn| {
+ if attn.sliding_window_size.is_some() {
+ local_rope.clone().expect("Local rope missing for sliding-window attention layer")
+ } else {
+ global_rope.clone().expect("Global rope missing for attention layer")
+ }
+ });
let layer_loader = decoder_weight_loader.subtree(&format!("layers.{}", layer_index)).unwrap();
- LayerExecutables::new(
- context,
- layer_config,
- layer_type,
- layer_index,
- decoder_config.model_dim,
- decoder_config.hidden_dim,
- decoder_config.num_heads,
- decoder_config.head_dim,
- decoder_config.num_groups,
- decoder_config.attention_scale,
- &layer_loader,
- rope_for_layer,
- )
+ LayerExecutables::new(context, tf, layer_config, layer_index, &layer_loader, rope_for_layer)
})
.collect::<Vec<_>>();
let norm_block = RMSNorm::new(
context,
norm_data_type,
- decoder_config.output_norm_config.clone(),
+ tf.output_norm_config.clone(),
&decoder_weight_loader.subtree("output_norm").unwrap(),
None,
true,
@@ -228,24 +173,10 @@ impl<B: Backend> Decoder<B> {
Rc::new(Rope::<B>::new(context, data_type, rope_type).expect("Failed to create Rope"))
}
- fn attention_data_type(decoder_config: &DecoderConfig) -> Option<DataType> {
- (0..decoder_config.num_layers).find_map(|layer_index| {
- let layer_config = decoder_config
- .layer_configs
- .as_ref()
- .map(|configs| &configs[layer_index])
- .unwrap_or(&decoder_config.layer_config);
- layer_config
- .attention_config()
- .map(|attention_config| attention_config.qkv_projection_config.activation_precision().into())
- })
- }
-
fn run_layers(
&self,
args: DecoderArguments<B>,
mut main: Allocation<B>,
- parameters: &EncodingParameters,
encoder: &mut Encoder<B>,
) -> Result<(Allocation<B>, Allocation<B>), DecoderError<B>> {
let DecoderArguments {
@@ -295,7 +226,6 @@ impl<B: Backend> Decoder<B> {
#[cfg(feature = "tracing")]
trace: layer_trace,
},
- parameters,
main,
&mut shortcut,
encoder,
@@ -310,11 +240,10 @@ impl<B: Backend> Decoder<B> {
&self,
args: DecoderArguments<B>,
token_ids: &Allocation<B>,
- parameters: &EncodingParameters,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, DecoderError<B>> {
let main = self.embed.encode_lookup(token_ids, args.batch_dim, encoder)?;
- let (main, _) = self.run_layers(args, main, parameters, encoder)?;
+ let (main, _) = self.run_layers(args, main, encoder)?;
Ok(main)
}
@@ -323,7 +252,6 @@ impl<B: Backend> Decoder<B> {
args: DecoderArguments<B>,
input: DecoderDecodeInput<'input, B>,
hidden_capture: Option<&mut Allocation<B>>,
- parameters: &EncodingParameters,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, DecoderError<B>> {
let sampling_start = args.sampling_start;
@@ -352,7 +280,6 @@ impl<B: Backend> Decoder<B> {
trace: trace.as_deref_mut(),
},
main,
- parameters,
encoder,
)?;
diff --git a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
index 6e107ef21..08beb2ac9 100644
--- a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
@@ -13,7 +13,7 @@ use crate::{
config::DeltaNetAttentionConfig,
encodable_block::linear::{Linear, LinearBlockError},
forward_pass::delta_net_layer::DeltaNetLayer,
- parameters::{ParameterLoaderError, ParameterTree, try_resolve_subtree},
+ parameters::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
@@ -85,15 +85,15 @@ impl<B: Backend> DeltaNetMixer<B> {
let has_bias = config.conv_config.has_biases;
// Load weights
- let mixer_tree = try_resolve_subtree(decoder_layer_loader, &["mixer"])?;
- let conv_tree = try_resolve_subtree(&mixer_tree, &["conv", "conv1d"])?;
+ let mixer_tree = decoder_layer_loader.subtree("mixer")?;
+ let conv_tree = mixer_tree.subtree("conv")?;
let (in_projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
&config.in_proj_config,
model_dim,
[config.total_proj_dim()],
context,
- &try_resolve_subtree(decoder_layer_loader, &["mixer.in_projection", "mixer.in_proj"])?,
+ &decoder_layer_loader.subtree("mixer.in_proj")?,
)
.map_err(|e| DeltaNetMixerError::InnerLinearError(Box::new(e)))?;
@@ -102,7 +102,7 @@ impl<B: Backend> DeltaNetMixer<B> {
config.value_dim(),
[model_dim],
context,
- &try_resolve_subtree(decoder_layer_loader, &["mixer.out_projection", "mixer.out_proj"])?,
+ &decoder_layer_loader.subtree("mixer.out_proj")?,
)
.map_err(|e| DeltaNetMixerError::InnerLinearError(Box::new(e)))?;
@@ -115,7 +115,7 @@ impl<B: Backend> DeltaNetMixer<B> {
let a_log = mixer_tree.leaf("a_log")?.read_allocation()?;
let dt_bias = mixer_tree.leaf("dt_bias")?.read_allocation()?;
- let norm_tree = try_resolve_subtree(&mixer_tree, &["norm", "inner_norm"])?;
+ let norm_tree = mixer_tree.subtree("norm")?;
let norm_weight = norm_tree.leaf("scales")?.read_allocation()?;
// Create kernels
diff --git a/crates/backend-uzu/src/encodable_block/embedding.rs b/crates/backend-uzu/src/encodable_block/embedding.rs
index 5d8e18bea..2a54304d4 100644
--- a/crates/backend-uzu/src/encodable_block/embedding.rs
+++ b/crates/backend-uzu/src/encodable_block/embedding.rs
@@ -16,7 +16,7 @@ use crate::{
},
},
config::EmbeddingConfig,
- parameters::{ParameterLeaf, ParameterLoaderError, ParameterTree},
+ parameters::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
@@ -31,13 +31,6 @@ pub enum EmbeddingError<B: Backend> {
ParameterError(#[from] ParameterLoaderError<B>),
#[error("Unsupported configuration: {0}")]
UnsupportedConfiguration(String),
- #[error("Invalid tensor: got {shape:?} @ {data_type:?}, expected {expected_shape:?} @ {expected_data_type:?}")]
- InvalidTensor {
- shape: Box<[usize]>,
- data_type: DataType,
- expected_shape: Box<[usize]>,
- expected_data_type: DataType,
- },
}
enum TiedEmbeddingType<B: Backend> {
@@ -127,52 +120,7 @@ const SPLIT_TREE_UNTIED_KEYS: UntiedWeightKeys = UntiedWeightKeys {
readout_biases: "biases",
};
-fn validate_tensor<'file, 'context, 'leaf, B: Backend>(
- weights_leaf: &ParameterLeaf<'file, 'context, 'leaf, B::Context>,
- expected_shape: [usize; 2],
- expected_data_type: DataType,
-) -> Result<(), EmbeddingError<B>> {
- let shape = weights_leaf.shape();
- let data_type = weights_leaf.data_type();
-
- if (shape, data_type) != (expected_shape.as_ref(), expected_data_type) {
- return Err(EmbeddingError::InvalidTensor {
- shape: shape.into(),
- data_type: weights_leaf.data_type(),
- expected_shape: expected_shape.into(),
- expected_data_type,
- });
- }
-
- Ok(())
-}
-
impl<B: Backend> Embedding<B> {
- fn activation_data_type(config: &EmbeddingConfig) -> DataType {
- match config {
- EmbeddingConfig::Tied {
- precision,
- ..
- }
- | EmbeddingConfig::Untied {
- precision,
- ..
- } => (*precision).into(),
- EmbeddingConfig::MLXQuantizedTied {
- activation_precision,
- ..
- }
- | EmbeddingConfig::MLXQuantizedUntied {
- activation_precision,
- ..
- }
- | EmbeddingConfig::MLXSemiQuantizedUntied {
- activation_precision,
- ..
- } => (*activation_precision).into(),
- }
- }
-
pub fn new(
context: &B::Context,
vocab_size: u32,
@@ -230,7 +178,7 @@ impl<B: Backend> Embedding<B> {
let data_type = (*precision).into();
let weights_leaf = lookup_tree.leaf("weights")?;
- validate_tensor(&weights_leaf, [vocab_size as usize, model_dim as usize], data_type)?;
+ weights_leaf.validate_shape(&[vocab_size as usize, model_dim as usize], data_type)?;
let weights = weights_leaf.read_allocation()?;
let lookup = <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)
@@ -252,9 +200,9 @@ impl<B: Backend> Embedding<B> {
let data_type = (*precision).into();
let input_weights_leaf = lookup_tree.leaf(untied_keys.lookup_weights)?;
- validate_tensor(&input_weights_leaf, [vocab_size as usize, model_dim as usize], data_type)?;
+ input_weights_leaf.validate_shape(&[vocab_size as usize, model_dim as usize], data_type)?;
let output_weights_leaf = readout_tree.leaf(untied_keys.readout_weights)?;
- validate_tensor(&output_weights_leaf, [vocab_size as usize, model_dim as usize], data_type)?;
+ output_weights_leaf.validate_shape(&[vocab_size as usize, model_dim as usize], data_type)?;
let input_weights = input_weights_leaf.read_allocation()?;
let output_weights = output_weights_leaf.read_allocation()?;
@@ -289,15 +237,12 @@ impl<B: Backend> Embedding<B> {
let num_groups = (model_dim as usize).div_ceil(*group_size);
let weights_leaf = lookup_tree.leaf("weights")?;
- validate_tensor(
- &weights_leaf,
- [vocab_size as usize, model_dim as usize / packing_divisor],
- storage_data_type,
- )?;
+ weights_leaf
+ .validate_shape(&[vocab_size as usize, model_dim as usize / packing_divisor], storage_data_type)?;
let scales_leaf = lookup_tree.leaf("scales")?;
- validate_tensor(&scales_leaf, [vocab_size as usize, num_groups], data_type)?;
+ scales_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let biases_leaf = lookup_tree.leaf("biases")?;
- validate_tensor(&biases_leaf, [vocab_size as usize, num_groups], data_type)?;
+ biases_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let weights = weights_leaf.read_allocation()?;
let scales = scales_leaf.read_allocation()?;
@@ -354,26 +299,20 @@ impl<B: Backend> Embedding<B> {
let num_groups = (model_dim as usize).div_ceil(*group_size);
let input_weights_leaf = lookup_tree.leaf(untied_keys.lookup_weights)?;
- validate_tensor(
- &input_weights_leaf,
- [vocab_size as usize, model_dim as usize / packing_divisor],
- storage_data_type,
- )?;
+ input_weights_leaf
+ .validate_shape(&[vocab_size as usize, model_dim as usize / packing_divisor], storage_data_type)?;
let input_scales_leaf = lookup_tree.leaf(untied_keys.lookup_scales)?;
- validate_tensor(&input_scales_leaf, [vocab_size as usize, num_groups], data_type)?;
+ input_scales_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let input_biases_leaf = lookup_tree.leaf(untied_keys.lookup_biases)?;
- validate_tensor(&input_biases_leaf, [vocab_size as usize, num_groups], data_type)?;
+ input_biases_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let output_weights_leaf = readout_tree.leaf(untied_keys.readout_weights)?;
- validate_tensor(
- &output_weights_leaf,
- [vocab_size as usize, model_dim as usize / packing_divisor],
- storage_data_type,
- )?;
+ output_weights_leaf
+ .validate_shape(&[vocab_size as usize, model_dim as usize / packing_divisor], storage_data_type)?;
let output_scales_leaf = readout_tree.leaf(untied_keys.readout_scales)?;
- validate_tensor(&output_scales_leaf, [vocab_size as usize, num_groups], data_type)?;
+ output_scales_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let output_biases_leaf = readout_tree.leaf(untied_keys.readout_biases)?;
- validate_tensor(&output_biases_leaf, [vocab_size as usize, num_groups], data_type)?;
+ output_biases_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let input_weights = input_weights_leaf.read_allocation()?;
let input_scales = input_scales_leaf.read_allocation()?;
@@ -439,18 +378,15 @@ impl<B: Backend> Embedding<B> {
let num_groups = (model_dim as usize).div_ceil(*group_size);
let input_weights_leaf = lookup_tree.leaf(untied_keys.lookup_weights)?;
- validate_tensor(&input_weights_leaf, [vocab_size as usize, model_dim as usize], data_type)?;
+ input_weights_leaf.validate_shape(&[vocab_size as usize, model_dim as usize], data_type)?;
let output_weights_leaf = readout_tree.leaf(untied_keys.readout_weights)?;
- validate_tensor(
- &output_weights_leaf,
- [vocab_size as usize, model_dim as usize / packing_divisor],
- storage_data_type,
- )?;
+ output_weights_leaf
+ .validate_shape(&[vocab_size as usize, model_dim as usize / packing_divisor], storage_data_type)?;
let output_scales_leaf = readout_tree.leaf(untied_keys.readout_scales)?;
- validate_tensor(&output_scales_leaf, [vocab_size as usize, num_groups], data_type)?;
+ output_scales_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let output_biases_leaf = readout_tree.leaf(untied_keys.readout_biases)?;
- validate_tensor(&output_biases_leaf, [vocab_size as usize, num_groups], data_type)?;
+ output_biases_leaf.validate_shape(&[vocab_size as usize, num_groups], data_type)?;
let input_weights = input_weights_leaf.read_allocation()?;
@@ -495,7 +431,7 @@ impl<B: Backend> Embedding<B> {
};
let input_scale = common.input_scale.unwrap_or(1.0);
- let activation_data_type = Self::activation_data_type(config);
+ let activation_data_type: DataType = config.activation_precision().into();
if let Some(logit_soft_cap) = common.logit_soft_cap {
return Err(EmbeddingError::UnsupportedConfiguration(format!("logit_soft_cap={logit_soft_cap:?}")));
diff --git a/crates/backend-uzu/src/encodable_block/layer/executables.rs b/crates/backend-uzu/src/encodable_block/layer/executables.rs
index 0bb930cb5..5d8c463af 100644
--- a/crates/backend-uzu/src/encodable_block/layer/executables.rs
+++ b/crates/backend-uzu/src/encodable_block/layer/executables.rs
@@ -10,10 +10,10 @@ use crate::forward_pass::traces::LayerActivationTrace;
use crate::{
DataType,
backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder},
- config::{DecoderLayerConfig, DecoderLayerType, MixerConfig},
+ config::{MixerConfig, TransformerConfig, TransformerLayerConfig},
encodable_block::{
- Attention, AttentionArguments, DeltaNetArguments, DeltaNetMixer, EncodingParameters, Linear, MambaArguments,
- MambaMixer, Mlp, QKNorm, RMSNorm, Rope, ShortConvArguments, ShortConvMixer,
+ Attention, AttentionArguments, DeltaNetArguments, DeltaNetMixer, Linear, MambaArguments, MambaMixer, Mlp,
+ QKNorm, RMSNorm, Rope, ShortConvArguments, ShortConvMixer,
},
forward_pass::{cache_layers::CacheLayer, state::RopeType},
parameters::ParameterTree,
@@ -24,9 +24,9 @@ pub struct LayerExecutables<B: Backend> {
pub layer_index: usize,
#[cfg(feature = "tracing")]
pub tensor_add: <B::Kernels as Kernels>::TensorAddBiasKernel,
- pub pre_attention_norm: RMSNorm<B>,
+ pub pre_mixer_norm: RMSNorm<B>,
pub(crate) mixer: MixerExecutables<B>,
- pub post_attention_norm: Option<RMSNorm<B>>,
+ pub post_mixer_norm: Option<RMSNorm<B>>,
pub pre_mlp_norm: RMSNorm<B>,
pub mlp: Box<dyn Mlp<B>>,
pub post_mlp_norm: Option<RMSNorm<B>>,
@@ -38,24 +38,13 @@ impl<B: Backend> LayerExecutables<B> {
#[allow(clippy::too_many_arguments)]
pub fn new(
context: &B::Context,
- layer_config: &DecoderLayerConfig,
- layer_type: &DecoderLayerType,
+ transformer_config: &TransformerConfig,
+ layer_config: &TransformerLayerConfig,
layer_index: usize,
- model_dim: usize,
- hidden_dim: usize,
- num_heads: usize,
- head_dim: usize,
- num_groups: usize,
- attention_scale: Option<f32>,
decoder_layer_loader: &ParameterTree<B::Context>,
rope: Option<Rc<Rope<B>>>,
) -> Self {
- let intermediate_data_type: DataType = match &layer_config.mixer_config {
- MixerConfig::Attention(attention) => attention.qkv_projection_config.activation_precision().into(),
- MixerConfig::Mamba(mamba) => mamba.in_projection_config.activation_precision().into(),
- MixerConfig::ShortConv(short_conv) => short_conv.in_projection_config.activation_precision().into(),
- MixerConfig::DeltaNet(config) => config.in_proj_config.activation_precision().into(),
- };
+ let intermediate_data_type: DataType = layer_config.mixer_config.activation_precision().into();
#[cfg(feature = "tracing")]
let tensor_add = TensorAddBiasKernel::new(context, intermediate_data_type, false)
@@ -65,28 +54,19 @@ impl<B: Backend> LayerExecutables<B> {
MixerConfig::Attention(attention_config) => {
let rope_block = rope.expect("RoPE encoder missing for attention layer");
- let layer_num_heads = attention_config.num_heads.unwrap_or(num_heads);
- let layer_num_groups = attention_config.num_groups.unwrap_or(num_groups);
- let layer_head_dim = attention_config.head_dim.unwrap_or(head_dim);
-
- let q_dim = layer_num_heads * layer_head_dim;
- let kv_dim = layer_num_groups * layer_head_dim;
+ let q_dim = attention_config.num_heads * attention_config.head_dim;
+ let kv_dim = attention_config.num_groups * attention_config.head_dim;
let (qkv_projection, input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
&attention_config.qkv_projection_config,
- model_dim,
+ transformer_config.model_dim,
[q_dim, kv_dim, kv_dim],
context,
&decoder_layer_loader.subtree("mixer.qkv_projection").unwrap(),
)
.expect("Failed to create qkv projection");
- let has_gate = attention_config.has_gate || attention_config.gate_projection_config.is_some();
- let gate_projection = has_gate.then(|| {
- let gate_config = attention_config
- .gate_projection_config
- .as_ref()
- .unwrap_or(&attention_config.qkv_projection_config);
+ let gate_projection = attention_config.gate_projection_config.as_ref().map(|gate_config| {
let gate_tree = decoder_layer_loader.subtree("mixer.gate_projection").unwrap();
match (input_hadamard_factors.is_some(), gate_config) {
(
@@ -109,7 +89,7 @@ impl<B: Backend> LayerExecutables<B> {
inner_config,
&inner_tree,
output_factors,
- model_dim,
+ transformer_config.model_dim,
q_dim,
)
},
@@ -122,7 +102,13 @@ impl<B: Backend> LayerExecutables<B> {
| (true, _) => {
panic!("attention qkv/gate projections must share input hadamard")
},
- (false, _) => <dyn Linear<B>>::new(gate_config, model_dim, [q_dim], context, &gate_tree),
+ (false, _) => <dyn Linear<B>>::new(
+ gate_config,
+ transformer_config.model_dim,
+ [q_dim],
+ context,
+ &gate_tree,
+ ),
}
.expect("Failed to create gate projection")
});
@@ -135,9 +121,9 @@ impl<B: Backend> LayerExecutables<B> {
attention_config.query_norm_config.clone(),
attention_config.key_norm_config.clone(),
&decoder_layer_loader.subtree("mixer").unwrap(),
- layer_num_heads,
- layer_num_groups,
- layer_head_dim,
+ attention_config.num_heads,
+ attention_config.num_groups,
+ attention_config.head_dim,
) {
Ok(qk_norm) => Some(qk_norm),
Err(e) => panic!("Failed to create QK norm kernel for layer {}: {:?}", layer_index, e),
@@ -149,22 +135,15 @@ impl<B: Backend> LayerExecutables<B> {
let out_projection = <dyn Linear<B>>::new(
&attention_config.out_projection_config,
q_dim,
- [model_dim],
+ [transformer_config.model_dim],
context,
&decoder_layer_loader.subtree("mixer.out_projection").unwrap(),
)
.expect("Failed to create out projection");
- let attention = Attention::new(
- context,
- intermediate_data_type,
- attention_scale,
- attention_config.has_sinks,
- attention_config.is_causal.unwrap_or(true),
- attention_config.sliding_window_size,
- has_gate,
- )
- .expect("Failed to create AttentionWrapper kernel");
+ let attention =
+ Attention::new(context, intermediate_data_type, attention_config, gate_projection.is_some())
+ .expect("Failed to create AttentionWrapper kernel");
(
MixerExecutables::Attention {
@@ -175,23 +154,17 @@ impl<B: Backend> LayerExecutables<B> {
use_rope: attention_config.use_rope,
attention,
out_projection,
- num_heads: layer_num_heads,
- num_groups: layer_num_groups,
- head_dim: layer_head_dim,
+ num_heads: attention_config.num_heads,
+ num_groups: attention_config.num_groups,
+ head_dim: attention_config.head_dim,
},
input_hadamard_factors,
)
},
MixerConfig::Mamba(mamba_config) => {
- let (mixer, input_hadamard_factors) = MambaMixer::new(
- context,
- layer_type.clone(),
- mamba_config.clone(),
- layer_index,
- model_dim,
- decoder_layer_loader,
- )
- .expect("Failed to create Mamba mixer");
+ let (mixer, input_hadamard_factors) =
+ MambaMixer::new(context, mamba_config.clone(), transformer_config.model_dim, decoder_layer_loader)
+ .expect("Failed to create Mamba mixer");
(
MixerExecutables::StateSpace {
mixer,
@@ -202,10 +175,8 @@ impl<B: Backend> LayerExecutables<B> {
MixerConfig::ShortConv(short_conv_config) => {
let (mixer, input_hadamard_factors) = ShortConvMixer::new(
context,
- layer_type.clone(),
short_conv_config.clone(),
- layer_index,
- model_dim,
+ transformer_config.model_dim,
decoder_layer_loader,
)
.expect("Failed to create ShortConv mixer");
@@ -217,9 +188,13 @@ impl<B: Backend> LayerExecutables<B> {
)
},
MixerConfig::DeltaNet(delta_net_config) => {
- let (mixer, input_hadamard_factors) =
- DeltaNetMixer::new(context, delta_net_config.clone(), model_dim, decoder_layer_loader)
- .expect("Failed to create DeltaNet mixer");
+ let (mixer, input_hadamard_factors) = DeltaNetMixer::new(
+ context,
+ delta_net_config.clone(),
+ transformer_config.model_dim,
+ decoder_layer_loader,
+ )
+ .expect("Failed to create DeltaNet mixer");
(
MixerExecutables::DeltaNet {
mixer,
@@ -229,10 +204,10 @@ impl<B: Backend> LayerExecutables<B> {
},
};
- let pre_attention_norm = RMSNorm::new(
+ let pre_mixer_norm = RMSNorm::new(
context,
intermediate_data_type,
- layer_config.pre_attention_norm_config.clone(),
+ layer_config.pre_mixer_norm_config.clone().expect("decoder layers require pre_mixer_norm_config"),
&decoder_layer_loader.subtree("pre_mixer_norm").unwrap(),
mixer_hadamard_factors,
true,
@@ -240,7 +215,7 @@ impl<B: Backend> LayerExecutables<B> {
)
.expect("Failed to create RMS norm kernel");
- let post_attention_norm = if let Some(norm_config) = &layer_config.post_attention_norm_config {
+ let post_mixer_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
Some(
RMSNorm::new(
context,
@@ -259,8 +234,8 @@ impl<B: Backend> LayerExecutables<B> {
let (mlp, mlp_input_hadamard_factors) = <dyn Mlp<B>>::new(
&layer_config.mlp_config,
- model_dim,
- hidden_dim,
+ transformer_config.model_dim,
+ transformer_config.hidden_dim,
context,
&decoder_layer_loader.subtree("mlp").unwrap(),
)
@@ -298,21 +273,20 @@ impl<B: Backend> LayerExecutables<B> {
layer_index,
#[cfg(feature = "tracing")]
tensor_add,
- pre_attention_norm,
+ pre_mixer_norm,
mixer,
- post_attention_norm,
+ post_mixer_norm,
pre_mlp_norm,
mlp,
post_mlp_norm,
#[cfg(feature = "tracing")]
- model_dim,
+ model_dim: transformer_config.model_dim,
}
}
pub fn encode(
&self,
args: LayerArguments<B>,
- parameters: &EncodingParameters,
input: Allocation<B>,
shortcut: &mut Allocation<B>,
encoder: &mut Encoder<B>,
@@ -336,7 +310,7 @@ impl<B: Backend> LayerExecutables<B> {
#[cfg(feature = "tracing")]
let mut layer_traces = trace;
- let mut hidden = self.pre_attention_norm.encode(&input, 0, batch_dim, Some(shortcut), encoder)?;
+ let mut hidden = self.pre_mixer_norm.encode(&input, 0, batch_dim, Some(shortcut), encoder)?;
#[cfg(feature = "tracing")]
if let Some(layer_traces) = layer_traces.as_deref_mut() {
encoder.encode_copy(shortcut, .., layer_traces.inputs.allocation_mut(), ..);
@@ -393,7 +367,6 @@ impl<B: Backend> LayerExecutables<B> {
.map(|layer| layer.as_transformer_mut().expect("Attention layer expects transformer cache"));
let attention_output = attention.encode(
AttentionArguments {
- projection_step: parameters.projection_step.unwrap_or(0),
token_subtrie_ranges,
attention_sinks,
kv_cache_layer,
@@ -470,8 +443,8 @@ impl<B: Backend> LayerExecutables<B> {
encoder.encode_copy(&hidden, .., layer_traces.attention.allocation_mut(), ..);
}
- if let Some(post_attention_norm) = &self.post_attention_norm {
- hidden = post_attention_norm.encode(&hidden, 0, batch_dim, None, encoder)?;
+ if let Some(post_mixer_norm) = &self.post_mixer_norm {
+ hidden = post_mixer_norm.encode(&hidden, 0, batch_dim, None, encoder)?;
#[cfg(feature = "tracing")]
if let Some(layer_traces) = layer_traces.as_deref_mut() {
encoder.encode_copy(&hidden, .., layer_traces.post_attention_norm.allocation_mut(), ..);
diff --git a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
index 380899244..5d5d1048d 100644
--- a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
+++ b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
@@ -17,7 +17,7 @@ use crate::{
Linear,
linear::{LinearBlockError, QuantizedLinear, QuantizedLinearError},
},
- prelude::{ParameterLeaf, ParameterLoaderError, ParameterTree},
+ prelude::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
@@ -28,13 +28,6 @@ pub enum QLoRALinearWrapperError<B: Backend> {
QuantizedLinearError(#[from] QuantizedLinearError<B>),
#[error("Parameter loader error: {0}")]
ParameterLoaderError(#[from] ParameterLoaderError<B>),
- #[error("Invalid tensor: got {shape:?} @ {data_type:?}, expected {expected_shape:?} @ {expected_data_type:?}")]
- InvalidTensor {
- shape: Box<[usize]>,
- data_type: DataType,
- expected_shape: Box<[usize]>,
- expected_data_type: DataType,
- },
#[error("Matmul error: {0}")]
MatmulError(#[from] MatmulError<B>),
}
@@ -51,27 +44,6 @@ pub struct QLoRALinearWrapper<B: Backend> {
data_type: DataType,
}
-// TODO: figure out how to make this generic over QLoRAWrapperError::InvalidTensor or make one global "Invalid Tensor" error and make this a common helper
-fn validate_tensor<'file, 'context, 'leaf, B: Backend>(
- weights_leaf: &ParameterLeaf<'file, 'context, 'leaf, B::Context>,
- expected_shape: [usize; 2],
- expected_data_type: DataType,
-) -> Result<(), QLoRALinearWrapperError<B>> {
- let shape = weights_leaf.shape();
- let data_type = weights_leaf.data_type();
-
- if (shape, data_type) != (expected_shape.as_ref(), expected_data_type) {
- return Err(QLoRALinearWrapperError::InvalidTensor {
- shape: shape.into(),
- data_type: weights_leaf.data_type(),
- expected_shape: expected_shape.into(),
- expected_data_type,
- });
- }
-
- Ok(())
-}
-
impl<B: Backend> QLoRALinearWrapper<B> {
pub fn new(
context: &B::Context,
@@ -97,11 +69,11 @@ impl<B: Backend> QLoRALinearWrapper<B> {
RefCell::new(<<B::Kernels as ManualKernels>::MatmulKernel as MatmulKernel>::new(context, data_type)?);
let adapter_down_leaf = parameter_tree.leaf("down_weights")?;
- validate_tensor(&adapter_down_leaf, [lora_rank as usize, input_dim as usize], data_type)?;
+ adapter_down_leaf.validate_shape(&[lora_rank, input_dim], data_type)?;
let adapter_down = adapter_down_leaf.read_allocation()?;
let adapter_up_leaf = parameter_tree.leaf("up_weights")?;
- validate_tensor(&adapter_up_leaf, [output_dim, lora_rank as usize], data_type)?;
+ adapter_up_leaf.validate_shape(&[output_dim, lora_rank], data_type)?;
let adapter_up = adapter_up_leaf.read_allocation()?;
Ok(Self {
diff --git a/crates/backend-uzu/src/encodable_block/mamba_mixer.rs b/crates/backend-uzu/src/encodable_block/mamba_mixer.rs
index b2b7bb66a..fb3d2791c 100644
--- a/crates/backend-uzu/src/encodable_block/mamba_mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/mamba_mixer.rs
@@ -14,18 +14,16 @@ use crate::{
ssd_prefill::{SSDPrefillArguments, SSDPrefillKernels, SSDPrefillMode},
},
},
- config::{DecoderLayerType, Mamba2Config},
+ config::Mamba2Config,
encodable_block::linear::{Linear, LinearBlockError},
forward_pass::ssm_layer::SSMLayer,
- parameters::{ParameterLoaderError, ParameterTree, try_resolve_subtree},
+ parameters::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
pub enum MambaMixerError<B: Backend> {
#[error("Backend error: {0}")]
BackendError(#[source] B::Error),
- #[error("Unsupported configuration: {0}")]
- UnsupportedConfiguration(String),
#[error("Linear error: {0}")]
LinearError(#[from] Box<LinearBlockError<B>>),
#[error("Parameter loader error: {0}")]
@@ -79,22 +77,14 @@ fn resolve_prefill_mode_from_env() -> SSDPrefillMode {
}
impl<B: Backend> MambaMixer<B> {
- #[allow(clippy::too_many_arguments)]
pub(crate) fn new(
context: &B::Context,
- layer_type: DecoderLayerType,
mamba_config: Mamba2Config,
- layer_index: usize,
model_dim: usize,
decoder_layer_loader: &ParameterTree<B::Context>,
) -> Result<(Self, Option<Allocation<B>>), MambaMixerError<B>> {
- if !matches!(layer_type, DecoderLayerType::StateSpace { .. }) {
- return Err(MambaMixerError::UnsupportedConfiguration(format!(
- "layer {layer_index} marked as transformer but Mamba mixer config provided"
- )));
- }
- let split_tree = try_resolve_subtree(decoder_layer_loader, &["mixer"])?;
- let conv_tree = try_resolve_subtree(&split_tree, &["conv", "conv1d"])?;
+ let split_tree = decoder_layer_loader.subtree("mixer")?;
+ let conv_tree = split_tree.subtree("conv")?;
let data_type: DataType = mamba_config.in_projection_config.activation_precision().into();
@@ -103,7 +93,7 @@ impl<B: Backend> MambaMixer<B> {
model_dim,
[mamba_config.conv_dim(), mamba_config.inner_dim(), mamba_config.num_heads],
context,
- &try_resolve_subtree(decoder_layer_loader, &["mixer.in_projection", "mixer.in_proj"])?,
+ &decoder_layer_loader.subtree("mixer.in_projection")?,
)
.map_err(|err| MambaMixerError::LinearError(Box::new(err)))?;
@@ -112,7 +102,7 @@ impl<B: Backend> MambaMixer<B> {
mamba_config.inner_dim(),
[model_dim],
context,
- &try_resolve_subtree(decoder_layer_loader, &["mixer.out_projection", "mixer.out_proj"])?,
+ &decoder_layer_loader.subtree("mixer.out_projection")?,
)
.map_err(|err| MambaMixerError::LinearError(Box::new(err)))?;
diff --git a/crates/backend-uzu/src/encodable_block/mlp/mod.rs b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
index b301563c3..cc86e0b21 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
@@ -42,46 +42,44 @@ impl<B: Backend> dyn Mlp<B> {
context: &B::Context,
parameter_tree: &ParameterTree<B::Context>,
) -> Result<(Box<dyn Mlp<B>>, Option<Allocation<B>>), MlpBlockError<B>> {
- if let MLPConfig::Dense(dense_config) = config {
- let data_type: DataType = dense_config.linear_config.activation_precision().into();
+ match config {
+ MLPConfig::Dense(dense_config) => {
+ let data_type: DataType = dense_config.linear_config.activation_precision().into();
- let (up_projection, up_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
- &dense_config.linear_config,
- model_dimension,
- [2 * hidden_dimension],
- context,
- &parameter_tree.subtree("up_projection")?,
- )?;
+ let (up_projection, up_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
+ &dense_config.linear_config,
+ model_dimension,
+ [2 * hidden_dimension],
+ context,
+ &parameter_tree.subtree("up_projection")?,
+ )?;
- let (down_projection, down_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
- &dense_config.linear_config,
- hidden_dimension,
- [model_dimension],
- context,
- &parameter_tree.subtree("down_projection")?,
- )?;
+ let (down_projection, down_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
+ &dense_config.linear_config,
+ hidden_dimension,
+ [model_dimension],
+ context,
+ &parameter_tree.subtree("down_projection")?,
+ )?;
- let gate = MlpGateActMulEncodable::new(
- context,
- data_type,
- dense_config.activation.clone(),
- hidden_dimension,
- down_input_hadamard_factors,
- )
- .map_err(MlpBlockError::BackendError)?;
+ let gate = MlpGateActMulEncodable::new(
+ context,
+ data_type,
+ dense_config.activation.clone(),
+ hidden_dimension,
+ down_input_hadamard_factors,
+ )
+ .map_err(MlpBlockError::BackendError)?;
- return Ok((
- Box::new(DenseMlp::new(up_projection, gate, down_projection, hidden_dimension, data_type)),
- up_input_hadamard_factors,
- ));
+ Ok((
+ Box::new(DenseMlp::new(up_projection, gate, down_projection, hidden_dimension, data_type)),
+ up_input_hadamard_factors,
+ ))
+ },
+ MLPConfig::MixtureOfExperts(mixture_of_experts_config) => Ok((
+ Box::new(MoeBlock::new(context, mixture_of_experts_config, model_dimension, parameter_tree)?),
+ None,
+ )),
}
-
- if let MLPConfig::MixtureOfExperts(mixture_of_experts_config) = config {
- let mixture_of_experts_block =
- MoeBlock::new(context, mixture_of_experts_config, model_dimension, hidden_dimension, parameter_tree)?;
- return Ok((Box::new(mixture_of_experts_block), None));
- }
-
- unreachable!("Unknown MLP config")
}
}
diff --git a/crates/backend-uzu/src/encodable_block/mlp/moe.rs b/crates/backend-uzu/src/encodable_block/mlp/moe.rs
index c85d49635..f206c9910 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/moe.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/moe.rs
@@ -60,6 +60,10 @@ pub enum MoeBlockError<B: Backend> {
ParameterLoaderError(#[from] ParameterLoaderError<B>),
#[error("MoE num_active_routed_experts must be greater than 0")]
InvalidActiveExpertCount,
+ #[error("MoE shared experts are not supported")]
+ UnsupportedSharedExperts,
+ #[error("MoE expert gate is not supported")]
+ UnsupportedExpertGate,
}
impl<B: Backend> MoeBlock<B> {
@@ -67,49 +71,33 @@ impl<B: Backend> MoeBlock<B> {
context: &B::Context,
moe_config: &MixtureOfExpertsConfig,
model_dim: usize,
- hidden_dim: usize,
parameter_tree: &ParameterTree<B::Context>,
) -> Result<Self, MoeBlockError<B>> {
if moe_config.num_active_routed_experts == 0 {
return Err(MoeBlockError::InvalidActiveExpertCount);
}
+ if moe_config.num_shared_experts != 0 {
+ return Err(MoeBlockError::UnsupportedSharedExperts);
+ }
+ if moe_config.gate_config.is_some() {
+ return Err(MoeBlockError::UnsupportedExpertGate);
+ }
let data_type: DataType = moe_config.expert_config.linear_config.activation_precision().into();
let router_data_type: DataType = moe_config.router_config.activation_precision().into();
let router_renorm = matches!(moe_config.routing_function, RoutingFunctionConfig::SoftmaxRouting);
- let router_tree = parameter_tree.subtree("router").map_err(MoeBlockError::ParameterLoaderError)?;
-
- let router = match &moe_config.router_config {
- LinearConfig::Quantized(_) => {
- unimplemented!("Quantized router with fused router+topk not yet supported");
- },
- LinearConfig::MLXQuantized(_) => {
- unimplemented!("MLX quantized router with fused router+topk not yet supported");
- },
- LinearConfig::FullPrecision {
- ..
- } => {
- let weights =
- router_tree.leaf("weights").map_err(MoeBlockError::ParameterLoaderError)?.read_allocation()?;
- let biases =
- router_tree.leaf("biases").map_err(MoeBlockError::ParameterLoaderError)?.read_allocation()?;
- RouterBlock {
- weights,
- biases,
- }
- },
- LinearConfig::QLoRA {
- ..
- } => {
- unimplemented!("QLoRA router not yet supported for MoE");
- },
- LinearConfig::RHTLinearWrapper {
- ..
- } => {
- unimplemented!("RHTLinearWrapper router not yet supported for MoE");
- },
+ let router_tree = parameter_tree.subtree("router")?;
+ let LinearConfig::FullPrecision {
+ ..
+ } = &moe_config.router_config
+ else {
+ unimplemented!("Only FullPrecision MoE router is supported; got {:?}", moe_config.router_config);
+ };
+ let router = RouterBlock {
+ weights: router_tree.leaf_allocation("weights")?,
+ biases: router_tree.leaf_allocation("biases")?,
};
let router_topk_kernel = <B::Kernels as Kernels>::MoeRouterTopKKernel::new(context, router_data_type)
@@ -129,41 +117,14 @@ impl<B: Backend> MoeBlock<B> {
let finalize_kernel =
<B::Kernels as Kernels>::MoeFinalizeKernel::new(context, data_type).map_err(MoeBlockError::BackendError)?;
- let experts_tree = parameter_tree.subtree("experts").map_err(MoeBlockError::ParameterLoaderError)?;
-
- let w13 = experts_tree
- .subtree("up_projection")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .leaf("weights")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .read_allocation()?;
-
- let w2 = experts_tree
- .subtree("down_projection")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .leaf("weights")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .read_allocation()?;
-
- let up_biases = experts_tree
- .subtree("up_projection")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .leaf("biases")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .read_allocation()?;
-
- let down_biases = experts_tree
- .subtree("down_projection")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .leaf("biases")
- .map_err(MoeBlockError::ParameterLoaderError)?
- .read_allocation()?;
-
+ let experts_tree = parameter_tree.subtree("experts")?;
+ let up_tree = experts_tree.subtree("up_projection")?;
+ let down_tree = experts_tree.subtree("down_projection")?;
let shared_weights = SharedMoeWeights {
- w13,
- w2,
- up_biases,
- down_biases,
+ w13: up_tree.leaf_allocation("weights")?,
+ w2: down_tree.leaf_allocation("weights")?,
+ up_biases: up_tree.leaf_allocation("biases")?,
+ down_biases: down_tree.leaf_allocation("biases")?,
};
Ok(Self {
@@ -179,7 +140,7 @@ impl<B: Backend> MoeBlock<B> {
finalize_kernel,
moe_config: moe_config.clone(),
model_dim,
- hidden_dim,
+ hidden_dim: moe_config.expert_hidden_dim,
data_type,
shared_weights,
})
@@ -324,11 +285,12 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {
let gating_code = Self::gating_code_from_activation(&self.moe_config.expert_config.activation.act_type());
- // Compute clipping values and alpha for expert kernels
- let gate_clip_min = self.moe_config.expert_config.gate_clipping[0].unwrap_or(f32::NEG_INFINITY);
- let gate_clip_max = self.moe_config.expert_config.gate_clipping[1].unwrap_or(f32::INFINITY);
- let up_clip_min = self.moe_config.expert_config.up_clipping[0];
- let up_clip_max = self.moe_config.expert_config.up_clipping[1];
+ let (gate_lo, gate_hi) = self.moe_config.expert_config.gate_clipping.unwrap_or_default();
+ let (up_lo, up_hi) = self.moe_config.expert_config.up_clipping.unwrap_or_default();
+ let gate_clip_min = gate_lo.unwrap_or(f32::NEG_INFINITY);
+ let gate_clip_max = gate_hi.unwrap_or(f32::INFINITY);
+ let up_clip_min = up_lo.unwrap_or(f32::NEG_INFINITY);
+ let up_clip_max = up_hi.unwrap_or(f32::INFINITY);
let silu_alpha = self.moe_config.expert_config.activation.alpha();
let mut row_expert_map = encoder.allocate_scratch(size_for_shape(&[total_rows], DataType::U32))?;
diff --git a/crates/backend-uzu/src/encodable_block/mod.rs b/crates/backend-uzu/src/encodable_block/mod.rs
index 18fd58478..896877c45 100644
--- a/crates/backend-uzu/src/encodable_block/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mod.rs
@@ -37,16 +37,3 @@ pub(crate) use sampling::SamplingInputs;
pub use sampling::{Sampling, SamplingArguments};
pub(crate) use short_conv_mixer::ShortConvArguments;
pub use short_conv_mixer::ShortConvMixer;
-
-#[derive(Clone)]
-pub struct EncodingParameters {
- pub projection_step: Option<usize>,
-}
-
-impl EncodingParameters {
- pub fn new() -> Self {
- Self {
- projection_step: None,
- }
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/qk_norm.rs b/crates/backend-uzu/src/encodable_block/qk_norm.rs
index a4c7b18c9..d0eeaf55d 100644
--- a/crates/backend-uzu/src/encodable_block/qk_norm.rs
+++ b/crates/backend-uzu/src/encodable_block/qk_norm.rs
@@ -1,5 +1,3 @@
-//! QK Normalization encodable.
-
use thiserror::Error;
use crate::{
@@ -17,16 +15,18 @@ pub enum QKNormError<B: Backend> {
#[error("Backend error: {0}")]
BackendError(#[source] B::Error),
#[error("Parameter loading error: {0}")]
- ParameterError(ParameterLoaderError<B>),
+ ParameterError(#[from] ParameterLoaderError<B>),
+}
+
+struct Head<B: Backend> {
+ kernel: <B::Kernels as Kernels>::QKNormKernel,
+ scales: Allocation<B>,
+ config: NormalizationConfig,
}
pub struct QKNorm<B: Backend> {
- query_kernel: Option<<B::Kernels as Kernels>::QKNormKernel>,
- key_kernel: Option<<B::Kernels as Kernels>::QKNormKernel>,
- query_config: Option<NormalizationConfig>,
- key_config: Option<NormalizationConfig>,
- query_scales: Option<Allocation<B>>,
- key_scales: Option<Allocation<B>>,
+ query: Option<Head<B>>,
+ key: Option<Head<B>>,
num_q_heads: usize,
num_kv_heads: usize,
head_dim: usize,
@@ -43,129 +43,86 @@ impl<B: Backend> QKNorm<B> {
num_kv_heads: usize,
head_dim: usize,
) -> Result<Self, QKNormError<B>> {
- let mut query_kernel = None;
- let mut key_kernel = None;
- let mut query_scales = None;
- let mut key_scales = None;
-
- // Setup query normalization if configured
- if let Some(ref q_config) = query_config {
- let scales = parameter_tree
- .leaf("query_norm.scales")
- .map_err(QKNormError::ParameterError)?
- .read_allocation()
- .map_err(QKNormError::ParameterError)?;
-
- let accumulation_data_type: DataType = q_config.accumulation_precision.into();
- let scale_data_type: DataType = q_config.scale_precision.into();
- let (input_type, scales_type, output_type) = match q_config.upcast_mode {
- UpcastMode::OnlyNormalization => (intermediate_data_type, scale_data_type, scale_data_type),
- UpcastMode::FullLayer => (intermediate_data_type, scale_data_type, scale_data_type),
- };
-
- let kernel = <B::Kernels as Kernels>::QKNormKernel::new(
- context,
- input_type,
- scales_type,
- output_type,
- accumulation_data_type,
- true,
- )
- .map_err(QKNormError::BackendError)?;
-
- query_kernel = Some(kernel);
- query_scales = Some(scales);
- }
-
- // Setup key normalization if configured
- if let Some(ref k_config) = key_config {
- let scales = parameter_tree
- .leaf("key_norm.scales")
- .map_err(QKNormError::ParameterError)?
- .read_allocation()
- .map_err(QKNormError::ParameterError)?;
-
- let accumulation_data_type: DataType = k_config.accumulation_precision.into();
- let scale_data_type: DataType = k_config.scale_precision.into();
- let (input_type, scales_type, output_type) = match k_config.upcast_mode {
- UpcastMode::OnlyNormalization => (intermediate_data_type, scale_data_type, scale_data_type),
- UpcastMode::FullLayer => (intermediate_data_type, scale_data_type, scale_data_type),
- };
-
- let kernel = <B::Kernels as Kernels>::QKNormKernel::new(
- context,
- input_type,
- scales_type,
- output_type,
- accumulation_data_type,
- true,
- )
- .map_err(QKNormError::BackendError)?;
-
- key_kernel = Some(kernel);
- key_scales = Some(scales);
- }
+ let query = query_config
+ .map(|cfg| Self::build_head(context, intermediate_data_type, cfg, parameter_tree, "query_norm.scales"))
+ .transpose()?;
+ let key = key_config
+ .map(|cfg| Self::build_head(context, intermediate_data_type, cfg, parameter_tree, "key_norm.scales"))
+ .transpose()?;
Ok(Self {
- query_kernel,
- key_kernel,
- query_config,
- key_config,
- query_scales,
- key_scales,
+ query,
+ key,
num_q_heads,
num_kv_heads,
head_dim,
})
}
+ fn build_head(
+ context: &B::Context,
+ intermediate_data_type: DataType,
+ config: NormalizationConfig,
+ parameter_tree: &ParameterTree<B::Context>,
+ scales_leaf: &str,
+ ) -> Result<Head<B>, QKNormError<B>> {
+ let scales = parameter_tree.leaf_allocation(scales_leaf)?;
+ let scale_data_type: DataType = config.scale_precision.into();
+ let accumulation_data_type: DataType = config.accumulation_precision.into();
+ let kernel = <B::Kernels as Kernels>::QKNormKernel::new(
+ context,
+ intermediate_data_type,
+ scale_data_type,
+ scale_data_type,
+ accumulation_data_type,
+ true,
+ )
+ .map_err(QKNormError::BackendError)?;
+ Ok(Head {
+ kernel,
+ scales,
+ config,
+ })
+ }
+
pub fn encode(
&self,
qkv: &mut Allocation<B>,
batch_dim: usize,
encoder: &mut Encoder<B>,
) -> Result<(), B::Error> {
- // Process query normalization if configured
- if let (Some(query_kernel), Some(query_scales), Some(query_config)) =
- (&self.query_kernel, &self.query_scales, &self.query_config)
- {
- query_kernel.encode(
- None::<&Allocation<B>>,
- query_scales,
- &mut *qkv,
- batch_dim as u32,
- self.num_q_heads as u32,
- self.num_kv_heads as u32,
- self.head_dim as u32,
- query_config.epsilon,
- query_config.scale_offset.unwrap_or(0.0),
- 0,
- self.num_q_heads as u32,
- query_config.upcast_mode == UpcastMode::FullLayer,
- encoder,
- );
+ if let Some(query) = &self.query {
+ self.encode_head(query, qkv, batch_dim, 0, self.num_q_heads as u32, encoder);
}
-
- // Process key normalization if configured
- if let (Some(key_kernel), Some(key_scales), Some(key_config)) =
- (&self.key_kernel, &self.key_scales, &self.key_config)
- {
- key_kernel.encode(
- None::<&Allocation<B>>,
- key_scales,
- &mut *qkv,
- batch_dim as u32,
- self.num_q_heads as u32,
- self.num_kv_heads as u32,
- self.head_dim as u32,
- key_config.epsilon,
- key_config.scale_offset.unwrap_or(0.0),
- self.num_q_heads as u32,
- self.num_kv_heads as u32,
- key_config.upcast_mode == UpcastMode::FullLayer,
- encoder,
- );
+ if let Some(key) = &self.key {
+ self.encode_head(key, qkv, batch_dim, self.num_q_heads as u32, self.num_kv_heads as u32, encoder);
}
Ok(())
}
+
+ fn encode_head(
+ &self,
+ head: &Head<B>,
+ qkv: &mut Allocation<B>,
+ batch_dim: usize,
+ range_start: u32,
+ range_end: u32,
+ encoder: &mut Encoder<B>,
+ ) {
+ head.kernel.encode(
+ None::<&Allocation<B>>,
+ &head.scales,
+ &mut *qkv,
+ batch_dim as u32,
+ self.num_q_heads as u32,
+ self.num_kv_heads as u32,
+ self.head_dim as u32,
+ head.config.epsilon,
+ head.config.scale_offset.unwrap_or(0.0),
+ range_start,
+ range_end,
+ head.config.upcast_mode == UpcastMode::FullLayer,
+ encoder,
+ );
+ }
}
diff --git a/crates/backend-uzu/src/encodable_block/rms_norm.rs b/crates/backend-uzu/src/encodable_block/rms_norm.rs
index a45d4fafb..67b3047e8 100644
--- a/crates/backend-uzu/src/encodable_block/rms_norm.rs
+++ b/crates/backend-uzu/src/encodable_block/rms_norm.rs
@@ -48,16 +48,11 @@ impl<B: Backend> RMSNorm<B> {
let accumulation_data_type: DataType = config.accumulation_precision.into();
let scale_data_type: DataType = config.scale_precision.into();
- let (input_type, scales_type, output_type) = match config.upcast_mode {
- UpcastMode::OnlyNormalization => (intermediate_data_type, scale_data_type, scale_data_type),
- UpcastMode::FullLayer => (intermediate_data_type, scale_data_type, scale_data_type),
- };
-
let kernel = <B::Kernels as Kernels>::RMSNormKernel::new(
context,
- input_type,
- scales_type,
- output_type,
+ intermediate_data_type,
+ scale_data_type,
+ scale_data_type,
accumulation_data_type,
false,
config.upcast_mode == UpcastMode::FullLayer,
@@ -72,8 +67,8 @@ impl<B: Backend> RMSNorm<B> {
config,
scales,
element_count,
- input_data_type: input_type,
- output_data_type: output_type,
+ input_data_type: intermediate_data_type,
+ output_data_type: scale_data_type,
hadamard_factors,
})
}
diff --git a/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs b/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs
index e7eca1e62..6fcb3fec9 100644
--- a/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs
@@ -7,10 +7,10 @@ use crate::{
Allocation, Backend, Encoder, Kernels,
kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},
},
- config::{DecoderLayerType, ShortConvConfig},
+ config::ShortConvConfig,
encodable_block::linear::{Linear, LinearBlockError},
forward_pass::short_conv_layer::ShortConvLayer,
- parameters::{ParameterLoaderError, ParameterTree, try_resolve_subtree},
+ parameters::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
@@ -50,17 +50,10 @@ pub(crate) struct ShortConvArguments<'a, B: Backend> {
impl<B: Backend> ShortConvMixer<B> {
pub fn new(
context: &B::Context,
- layer_type: DecoderLayerType,
short_conv_config: ShortConvConfig,
- layer_index: usize,
model_dim: usize,
decoder_layer_loader: &ParameterTree<B::Context>,
) -> Result<(Self, Option<Allocation<B>>), ShortConvMixerError<B>> {
- if !matches!(layer_type, DecoderLayerType::ShortConv { .. }) {
- return Err(ShortConvMixerError::UnsupportedConfiguration(format!(
- "layer {layer_index} marked as non-ShortConv but ShortConv config provided"
- )));
- }
if short_conv_config.kernel_size < 2 {
return Err(ShortConvMixerError::UnsupportedConfiguration(format!(
"kernel_size must be >= 2, got {}",
@@ -68,8 +61,8 @@ impl<B: Backend> ShortConvMixer<B> {
)));
}
- let mixer_tree = try_resolve_subtree(decoder_layer_loader, &["mixer"])?;
- let conv_tree = try_resolve_subtree(&mixer_tree, &["conv"])?;
+ let mixer_tree = decoder_layer_loader.subtree("mixer")?;
+ let conv_tree = mixer_tree.subtree("conv")?;
let data_type: DataType = short_conv_config.in_projection_config.activation_precision().into();
@@ -78,7 +71,7 @@ impl<B: Backend> ShortConvMixer<B> {
model_dim,
[model_dim * 3],
context,
- &try_resolve_subtree(&mixer_tree, &["in_projection", "in_proj"])?,
+ &mixer_tree.subtree("in_projection")?,
)
.map_err(|err| ShortConvMixerError::LinearError(Box::new(err)))?;
@@ -87,7 +80,7 @@ impl<B: Backend> ShortConvMixer<B> {
model_dim,
[model_dim],
context,
- &try_resolve_subtree(&mixer_tree, &["out_projection", "out_proj"])?,
+ &mixer_tree.subtree("out_projection")?,
)
.map_err(|err| ShortConvMixerError::LinearError(Box::new(err)))?;
diff --git a/crates/backend-uzu/src/forward_pass/cache_layers.rs b/crates/backend-uzu/src/forward_pass/cache_layers.rs
index 26b06f4ab..94e314a36 100644
--- a/crates/backend-uzu/src/forward_pass/cache_layers.rs
+++ b/crates/backend-uzu/src/forward_pass/cache_layers.rs
@@ -3,7 +3,7 @@ use std::cell::Cell;
use crate::{
array::size_for_shape,
backends::common::{AllocationType, Backend, Context, Encoder, kernel::kv_cache_update::KVCacheUpdate},
- config::DecoderLayerType,
+ config::MixerConfig,
forward_pass::{
delta_net_layer::DeltaNetLayer,
kv_cache_layer::{KVCacheLayer, KVCacheLayerState, KVSlice},
@@ -107,11 +107,11 @@ impl<B: Backend> CacheLayers<B> {
model_shape.kv_cache_layer_shapes(max_prefix_length, max_suffix_length).collect();
let mut data: Box<[CacheLayer<B>]> = model_shape
- .layer_types()
+ .layer_mixers()
.iter()
.enumerate()
- .map(|(layer_index, layer_type)| match layer_type {
- DecoderLayerType::Transformer => {
+ .map(|(layer_index, mixer)| match mixer {
+ MixerConfig::Attention(_) => {
let shape = kv_shapes[layer_index];
let window_length = model_shape.sliding_window_length_per_layer[layer_index]
.filter(|&window_size| window_size < total_context_length);
@@ -141,16 +141,9 @@ impl<B: Backend> CacheLayers<B> {
data_type: model_shape.kv_cache_data_type(),
})
},
- DecoderLayerType::StateSpace {
- conv_dim,
- kernel_size,
- state_dim,
- num_heads,
- head_dim,
- ..
- } => {
- let conv_shape = [*conv_dim, kernel_size.saturating_sub(1)];
- let ssm_shape = [*num_heads, *head_dim, *state_dim];
+ MixerConfig::Mamba(c) => {
+ let conv_shape = [c.conv_dim(), c.kernel_size.saturating_sub(1)];
+ let ssm_shape = [c.num_heads, c.head_dim, c.state_dim];
let dtype = model_shape.activation_data_type();
let conv_bytes = size_for_shape(&conv_shape, dtype);
let ssm_bytes = size_for_shape(&ssm_shape, dtype);
@@ -169,12 +162,10 @@ impl<B: Backend> CacheLayers<B> {
data_type: dtype,
})
},
- DecoderLayerType::ShortConv {
- kernel_size,
- } => {
- assert!(*kernel_size >= 2, "ShortConv kernel_size must be >= 2, got {}", kernel_size);
- let conv_shape = [model_shape.model_dim(), kernel_size - 1];
- let suffix_state_shape = [max_suffix_length, model_shape.model_dim(), kernel_size - 1];
+ MixerConfig::ShortConv(c) => {
+ assert!(c.kernel_size >= 2, "ShortConv kernel_size must be >= 2, got {}", c.kernel_size);
+ let conv_shape = [model_shape.model_dim(), c.kernel_size - 1];
+ let suffix_state_shape = [max_suffix_length, model_shape.model_dim(), c.kernel_size - 1];
let dtype = model_shape.activation_data_type();
let conv_bytes = size_for_shape(&conv_shape, dtype);
let suffix_bytes = size_for_shape(&suffix_state_shape, dtype);
@@ -193,16 +184,9 @@ impl<B: Backend> CacheLayers<B> {
suffix_state_valid_len: Cell::new(0),
})
},
- DecoderLayerType::DeltaNet {
- conv_dim,
- kernel_size,
- num_heads,
- head_dim,
- value_head_dim,
- ..
- } => {
- let conv_shape = [*conv_dim, kernel_size.saturating_sub(1)];
- let ssm_shape = [*num_heads, *value_head_dim, *head_dim];
+ MixerConfig::DeltaNet(c) => {
+ let conv_shape = [c.conv_dim(), c.kernel_size.saturating_sub(1)];
+ let ssm_shape = [c.num_heads, c.value_head_dim, c.head_dim];
let dtype = model_shape.activation_data_type();
let conv_bytes = size_for_shape(&conv_shape, dtype);
let ssm_bytes = size_for_shape(&ssm_shape, dtype);
diff --git a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs b/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
index a3dec827a..6a32cf07f 100644
--- a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
+++ b/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
@@ -105,21 +105,6 @@ impl<B: Backend> KVCacheLayer<B> {
}
}
- pub fn projected_segment_prefix_length(
- &self,
- projection_step: usize,
- ) -> usize {
- match &self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => *prefix_len + projection_step,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => *window_length,
- }
- }
-
pub fn window_length(&self) -> Option<usize> {
match &self.state {
KVCacheLayerState::Full {
diff --git a/crates/backend-uzu/src/forward_pass/model_shape.rs b/crates/backend-uzu/src/forward_pass/model_shape.rs
index d9a47b659..b7e531b50 100644
--- a/crates/backend-uzu/src/forward_pass/model_shape.rs
+++ b/crates/backend-uzu/src/forward_pass/model_shape.rs
@@ -1,6 +1,6 @@
use crate::{
DataType,
- config::{DecoderConfig, DecoderLayerType, LinearConfig, MLPConfig, MixerConfig},
+ config::{DecoderConfig, MLPConfig, MixerConfig},
};
#[derive(Debug, Clone)]
@@ -10,190 +10,63 @@ pub struct ModelShape {
vocabulary_size: usize,
model_dim: usize,
- hidden_dim: usize,
context_length: usize,
- num_heads: usize,
num_groups: usize,
head_dim: usize,
pub num_layers: usize,
pub sliding_window_length_per_layer: Box<[Option<usize>]>,
- pub layer_types: Box<[DecoderLayerType]>,
- max_mamba_heads: usize,
- max_mamba_groups: usize,
- max_mamba_head_dim: usize,
- max_mamba_conv_dim: usize,
- max_mamba_state_dim: usize,
- max_mamba_kernel_size: usize,
+ layer_mixers: Box<[MixerConfig]>,
max_rope_dim: usize,
- max_lora_intermediate: Option<usize>,
- has_gate: bool,
- max_delta_net_kernel_size: usize,
- max_delta_net_key_dim: usize,
- max_delta_net_num_heads: usize,
- max_qkv_dim: usize,
}
impl ModelShape {
pub fn from_decoder_config(decoder_config: &DecoderConfig) -> Self {
- let activation_type: DataType = match &decoder_config.layer_config.mlp_config {
- crate::config::MLPConfig::Dense(d) => d.linear_config.activation_precision().into(),
- crate::config::MLPConfig::MixtureOfExperts(m) => {
- m.expert_config.linear_config.activation_precision().into()
- },
- };
- let num_layers = decoder_config.num_layers;
- let layer_types: Box<[DecoderLayerType]> = if let Some(layer_types) = &decoder_config.layer_types {
- assert_eq!(
- layer_types.len(),
- num_layers,
- "layer_types entry count ({}) must equal num_layers ({})",
- layer_types.len(),
- num_layers
- );
- layer_types.clone()
- } else {
- vec![DecoderLayerType::Transformer; num_layers].into_boxed_slice()
- };
- let mut max_mamba_heads = 0;
- let mut max_mamba_groups = 0;
- let mut max_mamba_head_dim = 0;
- let mut max_mamba_conv_dim = 0;
- let mut max_mamba_state_dim = 0;
- let mut max_mamba_kernel_size = 0;
- for layer in layer_types.iter() {
- if let DecoderLayerType::StateSpace {
- conv_dim,
- kernel_size,
- state_dim,
- num_heads,
- num_groups,
- head_dim,
- ..
- } = layer
- {
- max_mamba_heads = max_mamba_heads.max(*num_heads);
- max_mamba_groups = max_mamba_groups.max(*num_groups);
- max_mamba_head_dim = max_mamba_head_dim.max(*head_dim);
- max_mamba_conv_dim = max_mamba_conv_dim.max(*conv_dim);
- max_mamba_state_dim = max_mamba_state_dim.max(*state_dim);
- max_mamba_kernel_size = max_mamba_kernel_size.max(*kernel_size as usize);
- }
- }
- let mut max_delta_net_kernel_size = 0usize;
- let mut max_delta_net_key_dim = 0usize;
- let mut max_delta_net_num_heads = 0usize;
- for layer in layer_types.iter() {
- if let DecoderLayerType::DeltaNet {
- kernel_size,
- num_heads,
- num_groups,
- head_dim,
- ..
- } = layer
- {
- max_delta_net_kernel_size = max_delta_net_kernel_size.max(*kernel_size);
- max_delta_net_key_dim = max_delta_net_key_dim.max(num_groups * head_dim);
- max_delta_net_num_heads = max_delta_net_num_heads.max(*num_heads);
- }
- }
-
- let mut max_rope_dim = 0usize;
- let mut max_lora_intermediate = None;
- let mut has_gate = false;
+ let tf = &decoder_config.transformer_config;
+ let layer_configs = &tf.layer_configs;
+ let num_layers = layer_configs.len();
- let all_layer_configs = decoder_config
- .layer_configs
- .as_ref()
- .map(|configs| configs.iter().collect::<Vec<_>>())
- .unwrap_or_else(|| vec![&decoder_config.layer_config; num_layers]);
-
- let mut max_qkv_dim = 0usize;
- for layer_config in &all_layer_configs {
- let mut linear_configs = Vec::new();
-
- match &layer_config.mixer_config {
- MixerConfig::Attention(attn) => {
- let hd = attn.head_dim.unwrap_or(decoder_config.head_dim);
- max_rope_dim = max_rope_dim.max(attn.partial_rope_dim.unwrap_or(hd));
- has_gate = has_gate || attn.has_gate || attn.gate_projection_config.is_some();
- linear_configs.extend([&attn.qkv_projection_config, &attn.out_projection_config]);
- },
- MixerConfig::Mamba(mamba) => {
- linear_configs.extend([&mamba.in_projection_config, &mamba.out_projection_config]);
- },
- MixerConfig::ShortConv(short_conv) => {
- linear_configs.extend([&short_conv.in_projection_config, &short_conv.out_projection_config]);
- },
- MixerConfig::DeltaNet(delta_net) => {
- linear_configs.extend([&delta_net.in_proj_config, &delta_net.out_proj_config]);
- },
- };
+ let (num_heads, num_groups, head_dim) =
+ decoder_config.first_attention().map(|a| (a.num_heads, a.num_groups, a.head_dim)).unwrap_or_default();
+ for attn in layer_configs.iter().filter_map(|l| l.mixer_config.as_attention()) {
+ assert_eq!(attn.num_heads, num_heads, "attention layers must share num_heads");
+ assert_eq!(attn.num_groups, num_groups, "attention layers must share num_groups");
+ assert_eq!(attn.head_dim, head_dim, "attention layers must share head_dim");
+ }
- match &layer_config.mlp_config {
- MLPConfig::Dense(dense) => {
- linear_configs.push(&dense.linear_config);
- },
- MLPConfig::MixtureOfExperts(moe) => {
- linear_configs.extend([&moe.router_config, &moe.expert_config.linear_config]);
- },
- };
+ let activation_type: DataType = match &layer_configs[0].mlp_config {
+ MLPConfig::Dense(d) => d.linear_config.activation_precision().into(),
+ MLPConfig::MixtureOfExperts(m) => m.expert_config.linear_config.activation_precision().into(),
+ };
- while let Some(linear_config) = linear_configs.pop() {
- match linear_config {
- LinearConfig::QLoRA {
- lora_rank,
- ..
- } => {
- max_lora_intermediate = Some(max_lora_intermediate.unwrap_or(0).max(*lora_rank));
- },
- LinearConfig::RHTLinearWrapper {
- inner_config,
- ..
- } => {
- linear_configs.push(inner_config.as_ref());
- },
- _ => (),
- };
+ let mut max_rope_dim = 0usize;
+ for layer in layer_configs.iter() {
+ if let MixerConfig::Attention(attn) = &layer.mixer_config
+ && attn.use_rope
+ {
+ max_rope_dim = max_rope_dim.max(attn.partial_rope_dim.unwrap_or(attn.head_dim));
}
}
- if max_qkv_dim == 0 {
- max_qkv_dim = (decoder_config.num_heads + 2 * decoder_config.num_groups) * decoder_config.head_dim;
- }
-
if max_rope_dim == 0 {
- max_rope_dim = decoder_config.head_dim;
+ max_rope_dim = head_dim;
}
+ let sliding_window_length_per_layer: Box<[Option<usize>]> =
+ layer_configs.iter().map(|l| l.mixer_config.sliding_window_size()).collect();
+ let layer_mixers: Box<[MixerConfig]> = layer_configs.iter().map(|l| l.mixer_config.clone()).collect();
+
Self {
activation_type,
kv_cache_type: activation_type,
vocabulary_size: decoder_config.vocab_size,
- model_dim: decoder_config.model_dim,
- hidden_dim: decoder_config.hidden_dim,
- context_length: decoder_config.context_length,
- num_heads: decoder_config.num_heads,
- num_groups: decoder_config.num_groups,
- head_dim: decoder_config.head_dim,
- num_layers: num_layers,
- sliding_window_length_per_layer: decoder_config
- .sliding_window_sizes
- .clone()
- .unwrap_or(vec![None; num_layers].into_boxed_slice()),
- layer_types,
- max_mamba_heads,
- max_mamba_groups,
- max_mamba_head_dim,
- max_mamba_conv_dim,
- max_mamba_state_dim,
- max_mamba_kernel_size,
+ model_dim: tf.model_dim,
+ context_length: tf.context_length,
+ num_groups,
+ head_dim,
+ num_layers,
+ sliding_window_length_per_layer,
+ layer_mixers,
max_rope_dim,
- max_lora_intermediate,
- has_gate,
- max_delta_net_kernel_size,
- max_delta_net_key_dim,
- max_delta_net_num_heads,
- max_qkv_dim,
}
}
@@ -205,14 +78,6 @@ impl ModelShape {
self.kv_cache_type
}
- pub fn num_heads(&self) -> usize {
- self.num_heads
- }
-
- pub fn head_dim(&self) -> usize {
- self.head_dim
- }
-
pub fn rope_dim(&self) -> usize {
self.max_rope_dim
}
@@ -225,15 +90,8 @@ impl ModelShape {
self.model_dim
}
- pub fn layer_type(
- &self,
- layer_index: usize,
- ) -> &DecoderLayerType {
- &self.layer_types[layer_index]
- }
-
- pub fn layer_types(&self) -> &[DecoderLayerType] {
- &self.layer_types
+ pub fn layer_mixers(&self) -> &[MixerConfig] {
+ &self.layer_mixers
}
pub fn main_shape(
@@ -258,27 +116,6 @@ impl ModelShape {
[suffix_length, bitmask_size]
}
- pub fn mlp_hidden_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, self.hidden_dim]
- }
-
- pub fn mlp_fused_up_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, 2 * self.hidden_dim]
- }
-
- pub fn qkv_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, self.max_qkv_dim]
- }
-
pub fn logits_shape(
&self,
suffix_length: usize,
@@ -286,56 +123,6 @@ impl ModelShape {
[suffix_length, self.vocabulary_size]
}
- pub fn attention_output_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- let attention_dim = self.num_heads * self.head_dim;
- let delta_net_dim = self
- .layer_types
- .iter()
- .filter_map(|lt| match lt {
- DecoderLayerType::DeltaNet {
- num_heads,
- value_head_dim,
- ..
- } => Some(num_heads * value_head_dim),
- _ => None,
- })
- .max()
- .unwrap_or(0);
- [suffix_length, attention_dim.max(delta_net_dim)]
- }
-
- pub fn gate_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- self.has_gate.then(|| [suffix_length, self.num_heads * self.head_dim])
- }
-
- pub fn rotated_queries_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 3] {
- [self.num_heads, suffix_length, self.head_dim]
- }
-
- pub fn rotated_keys_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 3] {
- [self.num_groups, suffix_length, self.head_dim]
- }
-
- pub fn extracted_values_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 3] {
- // Values share the same grouping as keys (grouped by num_groups)
- [self.num_groups, suffix_length, self.head_dim]
- }
-
pub fn kv_cache_layer_shapes(
&self,
max_prefix_length: usize,
@@ -350,348 +137,4 @@ impl ModelShape {
pub fn context_length(&self) -> usize {
self.context_length
}
-
- pub fn attention_partials_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 1] {
- const TOTAL_BLOCKS_COUNT: usize = 32;
- [self.num_heads * suffix_length * TOTAL_BLOCKS_COUNT * self.head_dim]
- }
-
- pub fn attention_sums_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 1] {
- const TOTAL_BLOCKS_COUNT: usize = 32;
- [self.num_heads * suffix_length * TOTAL_BLOCKS_COUNT]
- }
-
- pub fn attention_maxs_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 1] {
- const TOTAL_BLOCKS_COUNT: usize = 32;
- [self.num_heads * suffix_length * TOTAL_BLOCKS_COUNT]
- }
-
- pub fn moe_topk_ids_shape(
- &self,
- suffix_length: usize,
- k: usize,
- ) -> [usize; 2] {
- [suffix_length, k]
- }
-
- pub fn moe_topk_probs_shape(
- &self,
- suffix_length: usize,
- k: usize,
- ) -> [usize; 2] {
- [suffix_length, k]
- }
-
- pub fn moe_counts_shape(
- &self,
- num_experts: usize,
- ) -> [usize; 1] {
- [num_experts]
- }
-
- pub fn moe_offsets_shape(
- &self,
- num_experts: usize,
- ) -> [usize; 1] {
- [num_experts + 1]
- }
-
- pub fn moe_sumk_shape(&self) -> [usize; 1] {
- [1]
- }
-
- pub fn moe_bucketed_token_ids_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 1] {
- [max_routed_tokens]
- }
-
- pub fn moe_bucketed_probs_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 1] {
- [max_routed_tokens]
- }
-
- pub fn moe_tok2row_shape(
- &self,
- suffix_length: usize,
- k: usize,
- ) -> [usize; 1] {
- [suffix_length * k]
- }
-
- pub fn moe_y_partial_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 2] {
- [max_routed_tokens, self.model_dim]
- }
-
- pub fn moe_hidden_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 2] {
- [max_routed_tokens, self.hidden_dim]
- }
-
- pub fn moe_x_perm_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 2] {
- [max_routed_tokens, self.model_dim]
- }
-
- pub fn moe_tile_map_shape(
- &self,
- max_routed_tokens: usize,
- ) -> [usize; 1] {
- // For tiled GEMM: max_routed_tokens * 3
- // For two-pass decode indirect dispatch: max_routed_tokens * h_blocks * 3
- // where h_blocks = (d_ff + 3) / 4
- // We size for the larger (two-pass decode)
- let d_ff = self.hidden_dim;
- if d_ff > 0 {
- let h_blocks = (d_ff + 3) / 4;
- [max_routed_tokens * h_blocks * 3]
- } else {
- [max_routed_tokens * 3]
- }
- }
-
- pub fn moe_dispatch_args_shape(&self) -> [usize; 1] {
- [3]
- }
-
- pub fn moe_total_tiles_shape(&self) -> [usize; 1] {
- // layout: [total_tiles, total_jobs,
- // nan_fc1_count, nan_fc2_count,
- // nan_fc1_bits, nan_fc2_bits,
- // nan_gate_bits, nan_up_bits]
- [8]
- }
-
- pub fn ssm_inproj_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- self.max_mamba_inproj_dim_internal().map(|dim| [suffix_length, dim])
- }
-
- pub fn has_state_space_layers(&self) -> bool {
- self.max_mamba_heads > 0
- }
-
- pub fn has_short_conv_layers(&self) -> bool {
- self.layer_types.iter().any(|layer_type| matches!(layer_type, DecoderLayerType::ShortConv { .. }))
- }
-
- pub fn has_delta_net_layers(&self) -> bool {
- self.max_delta_net_kernel_size > 0
- }
-
- pub fn delta_net_prep_qk_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 1]> {
- if self.has_delta_net_layers() {
- Some([suffix_length * self.max_delta_net_key_dim])
- } else {
- None
- }
- }
-
- pub fn delta_net_prep_beta_decay_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 1]> {
- if self.has_delta_net_layers() {
- Some([suffix_length * self.max_delta_net_num_heads])
- } else {
- None
- }
- }
-
- fn max_delta_net_padded_stride(&self) -> usize {
- self.layer_types
- .iter()
- .filter_map(|lt| match lt {
- DecoderLayerType::DeltaNet {
- conv_dim,
- num_heads,
- value_head_dim,
- ..
- } => {
- let value_dim = num_heads * value_head_dim;
- Some(conv_dim + value_dim + 2 * num_heads)
- },
- _ => None,
- })
- .max()
- .unwrap_or(0)
- }
-
- pub fn max_mamba_conv_dim(&self) -> Option<usize> {
- if self.max_mamba_conv_dim == 0 {
- None
- } else {
- Some(self.max_mamba_conv_dim)
- }
- }
-
- pub fn max_mamba_state_dim(&self) -> Option<usize> {
- if self.max_mamba_state_dim == 0 {
- None
- } else {
- Some(self.max_mamba_state_dim)
- }
- }
-
- pub fn max_mamba_kernel_size(&self) -> Option<usize> {
- if self.max_mamba_kernel_size == 0 {
- None
- } else {
- Some(self.max_mamba_kernel_size)
- }
- }
-
- pub fn ssm_packed_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- self.max_mamba_conv_dim().map(|dim| [suffix_length, dim])
- }
-
- pub fn ssm_conv_padded_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- let mamba = match (self.max_mamba_conv_dim(), self.max_mamba_kernel_size()) {
- (Some(conv_dim), Some(kernel_size)) if kernel_size > 0 => Some((suffix_length + kernel_size - 1, conv_dim)),
- _ => None,
- };
- let delta_net = if self.has_delta_net_layers() {
- let state_stride = self.max_delta_net_kernel_size.saturating_sub(1);
- let max_padded_stride = self.max_delta_net_padded_stride();
- Some((suffix_length + state_stride, max_padded_stride))
- } else {
- None
- };
- match (mamba, delta_net) {
- (Some((rows_m, cols_m)), Some((rows_d, cols_d))) => Some([rows_m.max(rows_d), cols_m.max(cols_d)]),
- (Some((rows, cols)), None) | (None, Some((rows, cols))) => Some([rows, cols]),
- (None, None) => None,
- }
- }
-
- pub fn short_conv_padded_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- if !self.has_short_conv_layers() {
- return None;
- }
-
- let max_kernel_size = self
- .layer_types
- .iter()
- .filter_map(|layer_type| match layer_type {
- DecoderLayerType::ShortConv {
- kernel_size,
- } => Some(*kernel_size),
- _ => None,
- })
- .max()
- .unwrap_or(0);
-
- let max_state_stride = max_kernel_size.saturating_sub(1);
- Some([suffix_length + max_state_stride, self.model_dim])
- }
-
- pub fn ssm_x_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 3]> {
- if self.has_state_space_layers() {
- Some([suffix_length, self.max_mamba_heads, self.max_mamba_head_dim])
- } else {
- None
- }
- }
-
- pub fn ssm_z_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 3]> {
- self.ssm_x_shape(suffix_length)
- }
-
- pub fn ssm_dt_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- if self.has_state_space_layers() {
- Some([suffix_length, self.max_mamba_heads])
- } else {
- None
- }
- }
-
- pub fn ssm_bc_shape(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 3]> {
- if self.has_state_space_layers() {
- self.max_mamba_state_dim().map(|state_dim| [suffix_length, self.max_mamba_groups, state_dim])
- } else {
- None
- }
- }
-
- pub fn lora_intermediate(
- &self,
- suffix_length: usize,
- ) -> Option<[usize; 2]> {
- self.max_lora_intermediate.map(|max_lora_intermediate| [suffix_length, max_lora_intermediate])
- }
-
- fn max_mamba_inproj_dim_internal(&self) -> Option<usize> {
- self.layer_types
- .iter()
- .filter_map(|layer_type| match layer_type {
- DecoderLayerType::StateSpace {
- conv_dim,
- num_heads,
- head_dim,
- ..
- } => {
- let inner_dim = num_heads * head_dim;
- Some(conv_dim + inner_dim + num_heads)
- },
- DecoderLayerType::ShortConv {
- ..
- } => Some(self.model_dim * 3),
- DecoderLayerType::DeltaNet {
- conv_dim,
- num_heads,
- value_head_dim,
- ..
- } => {
- let value_dim = num_heads * value_head_dim;
- Some(conv_dim + value_dim + 2 * num_heads)
- },
- _ => None,
- })
- .max()
- }
}
diff --git a/crates/backend-uzu/src/forward_pass/state/shared_buffers.rs b/crates/backend-uzu/src/forward_pass/state/shared_buffers.rs
index 6011bbd2c..dc56d0475 100644
--- a/crates/backend-uzu/src/forward_pass/state/shared_buffers.rs
+++ b/crates/backend-uzu/src/forward_pass/state/shared_buffers.rs
@@ -13,7 +13,7 @@ use crate::{
pub struct SharedBuffers<B: Backend> {
pub global_rope: Option<RopeBuffers<B>>,
pub local_rope: Option<RopeBuffers<B>>,
- pub attention_sinks: Option<Vec<Allocation<B>>>,
+ pub attention_sinks: Box<[Option<Allocation<B>>]>,
}
impl<B: Backend> SharedBuffers<B> {
@@ -22,16 +22,19 @@ impl<B: Backend> SharedBuffers<B> {
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
) -> Self {
- let global_rope = decoder_config.global_rope_config.is_some().then(|| RopeBuffers::new(context, model_shape));
+ let tf = &decoder_config.transformer_config;
+ let global_rope = tf.global_rope_config.is_some().then(|| RopeBuffers::new(context, model_shape));
+ let local_rope = tf.local_rope_config.is_some().then(|| RopeBuffers::new(context, model_shape));
- let local_rope = decoder_config.local_rope_config.is_some().then(|| RopeBuffers::new(context, model_shape));
-
- let attention_sinks = decoder_config.layer_config.attention_config().is_some_and(|c| c.has_sinks).then(|| {
- let num_heads = decoder_config.num_heads;
- (0..decoder_config.num_layers)
- .map(|_| context.create_array_uninitialized(&[num_heads], DataType::F32).into_allocation())
- .collect()
- });
+ let attention_sinks = tf
+ .layer_configs
+ .iter()
+ .map(|layer| {
+ let attn = layer.mixer_config.as_attention()?;
+ attn.has_sinks
+ .then(|| context.create_array_uninitialized(&[attn.num_heads], DataType::F32).into_allocation())
+ })
+ .collect();
Self {
global_rope,
@@ -53,41 +56,42 @@ impl<B: Backend> SharedBuffers<B> {
local_rope.update_data(&transformer_tree, "local_rope");
}
- if let Some(sinks_vec) = &mut self.attention_sinks {
- for (layer_idx, sink_cell) in sinks_vec.iter_mut().enumerate() {
- let layer_tree = transformer_tree.subtree(&format!("layers.{}", layer_idx)).unwrap();
- let attn_tree = layer_tree.subtree("mixer").unwrap();
- let sinks_arr = attn_tree.leaf_array("sinks").unwrap();
- let dst_slice = unsafe {
- let buffer_range = sink_cell.as_buffer_range_mut();
- let range = buffer_range.range();
- std::slice::from_raw_parts_mut(
- (buffer_range.buffer().cpu_ptr().as_ptr() as *mut u8).add(range.start) as *mut f32,
- range.len() / std::mem::size_of::<f32>(),
- )
- };
+ for (layer_idx, sink_cell) in self.attention_sinks.iter_mut().enumerate() {
+ let Some(sink_cell) = sink_cell.as_mut() else {
+ continue;
+ };
+ let layer_tree = transformer_tree.subtree(&format!("layers.{}", layer_idx)).unwrap();
+ let attn_tree = layer_tree.subtree("mixer").unwrap();
+ let sinks_arr = attn_tree.leaf_array("sinks").unwrap();
+ let dst_slice = unsafe {
+ let buffer_range = sink_cell.as_buffer_range_mut();
+ let range = buffer_range.range();
+ std::slice::from_raw_parts_mut(
+ (buffer_range.buffer().cpu_ptr().as_ptr() as *mut u8).add(range.start) as *mut f32,
+ range.len() / std::mem::size_of::<f32>(),
+ )
+ };
- match sinks_arr.data_type() {
- DataType::F32 => {
- let src = sinks_arr.as_slice::<f32>();
- dst_slice.copy_from_slice(src);
- },
- DataType::BF16 => {
- let src = sinks_arr.as_slice::<bf16>();
- for (dst_val, src_val) in dst_slice.iter_mut().zip(src.iter()) {
- *dst_val = f32::from(*src_val);
- }
- },
- DataType::F16 => {
- let src = sinks_arr.as_slice::<f16>();
- for (dst_val, src_val) in dst_slice.iter_mut().zip(src.iter()) {
- *dst_val = f32::from(*src_val);
- }
- },
- other => {
- panic!("Unsupported attention sink data type: {:?}", other);
- },
- }
+ match sinks_arr.data_type() {
+ DataType::F32 => {
+ let src = sinks_arr.as_slice::<f32>();
+ dst_slice.copy_from_slice(src);
+ },
+ DataType::BF16 => {
+ let src = sinks_arr.as_slice::<bf16>();
+ for (dst_val, src_val) in dst_slice.iter_mut().zip(src.iter()) {
+ *dst_val = f32::from(*src_val);
+ }
+ },
+ DataType::F16 => {
+ let src = sinks_arr.as_slice::<f16>();
+ for (dst_val, src_val) in dst_slice.iter_mut().zip(src.iter()) {
+ *dst_val = f32::from(*src_val);
+ }
+ },
+ other => {
+ panic!("Unsupported attention sink data type: {:?}", other);
+ },
}
}
}
@@ -116,6 +120,6 @@ impl<B: Backend> SharedBuffers<B> {
&self,
layer_index: usize,
) -> Option<&Allocation<B>> {
- self.attention_sinks.as_ref().map(|sinks| &sinks[layer_index])
+ self.attention_sinks.get(layer_index)?.as_ref()
}
}
diff --git a/crates/backend-uzu/src/inference/model_metadata.rs b/crates/backend-uzu/src/inference/model_metadata.rs
index 29d5e1175..d45b4cd09 100644
--- a/crates/backend-uzu/src/inference/model_metadata.rs
+++ b/crates/backend-uzu/src/inference/model_metadata.rs
@@ -1,5 +1,6 @@
use std::{fs::File, io::BufReader, path::Path};
+use serde::de::IgnoredAny;
use shoji::types::model::ModelSpecialization;
use crate::config::{ModelMetadata as InnerModelMetadata, ModelType};
@@ -12,7 +13,7 @@ pub struct ModelMetadata {
pub fn resolve_model_metadata(model_path: &Path) -> Option<ModelMetadata> {
let config_path = model_path.join("config.json");
let file = File::open(&config_path).ok()?;
- let metadata: InnerModelMetadata = serde_json::from_reader(BufReader::new(file)).ok()?;
+ let metadata: InnerModelMetadata<IgnoredAny> = serde_json::from_reader(BufReader::new(file)).ok()?;
let specialization = match metadata.model_type {
ModelType::LanguageModel => ModelSpecialization::Chat {},
ModelType::ClassifierModel => ModelSpecialization::Classification {},
diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rs
index 79c13d59b..df753ee5e 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator.rs
@@ -14,8 +14,8 @@ use crate::{
Allocation, AsBufferRangeRef, Backend, CommandBuffer, Context, DenseBuffer, Encoder, Pending,
kernel::TokenCopySampledKernel,
},
- config::ModelMetadata,
- encodable_block::{DecoderDecodeInput, EncodingParameters, SamplingArguments, SamplingInputs},
+ config::{LanguageModelConfig, ModelMetadata},
+ encodable_block::{DecoderDecodeInput, SamplingArguments, SamplingInputs},
forward_pass::{cache_layers::CacheLayersSlice, kv_cache_layer::INVALID_POSITION, token_inputs::TokenInputs},
language_model::grammar::CompiledGrammar,
session::{
@@ -95,7 +95,6 @@ pub trait LanguageModelGeneratorTrait {
pass_idx: usize,
);
- fn clear_cache(&mut self);
fn reset_state(&mut self);
fn peak_memory_usage(&self) -> Option<usize>;
@@ -512,7 +511,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
sampling_length,
false,
Some(sampling_method),
- &EncodingParameters::new(),
Some(sampling_inputs),
)?;
@@ -591,8 +589,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
}
}
- fn clear_cache(&mut self) {}
-
fn reset_state(&mut self) {
self.context.cache_layers.borrow_mut().clear(self.context.context.as_ref());
self.tokens.clear();
@@ -664,7 +660,7 @@ impl<B: Backend> LanguageModelGenerator<B> {
pub fn new(
model_path: &Path,
decoding_config: DecodingConfig,
- model_metadata: &ModelMetadata,
+ model_metadata: &ModelMetadata<LanguageModelConfig>,
) -> Result<Self, Error> {
let gpu_capture = GpuCaptureManager::new();
@@ -715,7 +711,6 @@ impl<B: Backend> LanguageModelGenerator<B> {
sampling_length,
is_prefilling,
sample.then_some(sampling_method),
- &EncodingParameters::new(),
sampling_inputs,
)?;
@@ -749,7 +744,6 @@ impl<B: Backend> LanguageModelGenerator<B> {
sampling_length: usize,
is_prefilling: bool,
sampling_method: Option<SamplingMethod>,
- parameters: &EncodingParameters,
sampling_inputs: Option<SamplingInputs<B>>,
) -> Result<ForwardPassResources<B>, Error> {
let mut sampling_output = sampling_method.map(|_| {
@@ -770,7 +764,7 @@ impl<B: Backend> LanguageModelGenerator<B> {
);
context
.executables
- .encode_prefill(decoder_arguments, token_inputs.token_ids(), parameters, encoder)
+ .encode_prefill(decoder_arguments, token_inputs.token_ids(), encoder)
.map_err(|e| Error::EncodeFailed(Box::new(e)))?;
} else {
let mut cache_layers = context.cache_layers.borrow_mut();
@@ -786,13 +780,7 @@ impl<B: Backend> LanguageModelGenerator<B> {
);
let mut retained_logits = context
.executables
- .encode_decode(
- decoder_arguments,
- DecoderDecodeInput::TokenIds(token_inputs.token_ids()),
- None,
- parameters,
- encoder,
- )
+ .encode_decode(decoder_arguments, DecoderDecodeInput::TokenIds(token_inputs.token_ids()), None, encoder)
.map_err(|e| Error::EncodeFailed(Box::new(e)))?;
let sampling_inputs = sampling_inputs.as_ref().expect("Sampling requires sampling inputs");
diff --git a/crates/backend-uzu/src/language_model/language_model_generator_context.rs b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
index a32b45032..10728a8b4 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator_context.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
@@ -120,19 +120,15 @@ impl<B: Backend> LanguageModelGeneratorContext<B> {
pub fn new(
model_path: &Path,
decoding_config: &DecodingConfig,
- model_metadata: &ModelMetadata,
+ model_metadata: &ModelMetadata<LanguageModelConfig>,
) -> Result<Self, Error> {
let context = B::Context::new().map_err(|e| Error::UnableToCreateContext(e.into()))?;
- // Extract language model config
- let language_model_config = model_metadata.model_config.as_language_model().ok_or(Error::UnableToLoadConfig)?;
+ let model_shape = ModelShape::from_decoder_config(&model_metadata.model_config.model_config);
- let decoder_config = language_model_config.decoder_config().map_err(|_| Error::UnableToLoadConfig)?;
- let model_shape = ModelShape::from_decoder_config(&decoder_config);
-
- let prefill_step_size = decoding_config.prefill_step_size.resolve(language_model_config);
+ let prefill_step_size = decoding_config.prefill_step_size.resolve(&model_metadata.model_config);
let generate_suffix_length = decoding_config.generate_suffix_length();
- let max_prefix_length: usize = decoding_config.context_length.resolve(language_model_config);
+ let max_prefix_length: usize = decoding_config.context_length.resolve(&model_metadata.model_config);
let max_suffix_length: usize = std::cmp::max(prefill_step_size, generate_suffix_length);
let weights_path = model_path.join("model.safetensors");
@@ -143,11 +139,12 @@ impl<B: Backend> LanguageModelGeneratorContext<B> {
let loader = ParameterLoader::new(&weights_file, context.as_ref()).map_err(|_| Error::UnableToLoadWeights)?;
let root_loader_view = loader.tree();
- let mut shared_buffers = SharedBuffers::new(context.as_ref(), &decoder_config, &model_shape);
+ let mut shared_buffers =
+ SharedBuffers::new(context.as_ref(), &model_metadata.model_config.model_config, &model_shape);
shared_buffers.update_data(&root_loader_view);
let shared_buffers = Rc::new(shared_buffers);
- let executables = Decoder::new(context.as_ref(), &decoder_config, &root_loader_view);
+ let executables = Decoder::new(context.as_ref(), &model_metadata.model_config.model_config, &root_loader_view);
let cache_layers = Rc::new(RefCell::new(CacheLayers::new(
context.as_ref(),
@@ -156,7 +153,8 @@ impl<B: Backend> LanguageModelGeneratorContext<B> {
max_suffix_length,
)));
- let intermediate_data_type: DataType = decoder_config.output_norm_config.scale_precision.into();
+ let intermediate_data_type: DataType =
+ model_metadata.model_config.model_config.transformer_config.output_norm_config.scale_precision.into();
let kv_cache_update = Box::new(
KVCacheUpdate::new(context.as_ref(), intermediate_data_type, max_prefix_length)
.map_err(|e| Error::UnableToCreateContext(e.into()))?,
@@ -177,7 +175,7 @@ impl<B: Backend> LanguageModelGeneratorContext<B> {
context,
cache_layers,
shared_buffers,
- model_config: language_model_config.clone(),
+ model_config: model_metadata.model_config.clone(),
model_shape,
executables,
kv_cache_update,
diff --git a/crates/backend-uzu/src/parameters/loader.rs b/crates/backend-uzu/src/parameters/loader.rs
index 9bf5c6e86..79965ab7b 100644
--- a/crates/backend-uzu/src/parameters/loader.rs
+++ b/crates/backend-uzu/src/parameters/loader.rs
@@ -62,6 +62,13 @@ pub enum ParameterLoaderError<B: Backend> {
BackendError(#[source] B::Error),
#[error("Failed to read data")]
ArrayLoadingError(#[from] std::io::Error),
+ #[error("Invalid tensor: got {shape:?} @ {data_type:?}, expected {expected_shape:?} @ {expected_data_type:?}")]
+ InvalidTensor {
+ shape: Box<[usize]>,
+ data_type: DataType,
+ expected_shape: Box<[usize]>,
+ expected_data_type: DataType,
+ },
}
pub struct ParameterLoader<'context, 'file, C: Context>
@@ -164,6 +171,24 @@ impl<'file, 'context, 'leaf, C: Context> ParameterLeaf<'file, 'context, 'leaf, C
self.metadata.size
}
+ pub fn validate_shape(
+ &self,
+ expected_shape: &[usize],
+ expected_data_type: DataType,
+ ) -> Result<(), ParameterLoaderError<C::Backend>> {
+ let shape = self.shape();
+ let data_type = self.data_type();
+ if (shape, data_type) != (expected_shape, expected_data_type) {
+ return Err(ParameterLoaderError::InvalidTensor {
+ shape: shape.into(),
+ data_type,
+ expected_shape: expected_shape.into(),
+ expected_data_type,
+ });
+ }
+ Ok(())
+ }
+
pub fn read_allocation(&self) -> Result<Allocation<C::Backend>, ParameterLoaderError<C::Backend>> {
let allocation = self
.loader
@@ -250,15 +275,3 @@ impl<'loader, C: Context> ParameterTree<'loader, C> {
self.loader.read_extract_at(&self.join_prefix(name), buf, shape, data_type)
}
}
-
-pub fn try_resolve_subtree<'tree, C: Context>(
- tree: &'tree ParameterTree<C>,
- candidates: &[&str],
-) -> Result<ParameterTree<'tree, C>, ParameterLoaderError<C::Backend>> {
- for candidate in candidates {
- if let Ok(subtree) = tree.subtree(candidate) {
- return Ok(subtree);
- }
- }
- Err(ParameterLoaderError::SubtreeNotFound(candidates.join(" or ")))
-}
diff --git a/crates/backend-uzu/src/parameters/mod.rs b/crates/backend-uzu/src/parameters/mod.rs
index a3b5e9087..b2715220f 100644
--- a/crates/backend-uzu/src/parameters/mod.rs
+++ b/crates/backend-uzu/src/parameters/mod.rs
@@ -3,5 +3,5 @@ mod safetensors_metadata;
// Re-export the safetensors header reader so other modules (e.g. decoder
// runner) can estimate parameter memory before creating a Context.
-pub use loader::{ParameterLeaf, ParameterLoader, ParameterLoaderError, ParameterTree, try_resolve_subtree};
+pub use loader::{ParameterLeaf, ParameterLoader, ParameterLoaderError, ParameterTree};
pub use safetensors_metadata::{HeaderLoadingError, read_metadata as read_safetensors_metadata};
diff --git a/crates/backend-uzu/src/session/chat_session.rs b/crates/backend-uzu/src/session/chat_session.rs
index 7915ae225..00ef87202 100644
--- a/crates/backend-uzu/src/session/chat_session.rs
+++ b/crates/backend-uzu/src/session/chat_session.rs
@@ -15,7 +15,7 @@ use tokenizers::Tokenizer;
use crate::{
backends::{common::Backend, select_backend},
- config::{MixerConfig, ModelMetadata},
+ config::{LanguageModelConfig, MixerConfig, ModelMetadata},
language_model::{
LanguageModelGenerator, LanguageModelGeneratorTrait,
grammar::{CompiledGrammar, create_compiled_grammar},
@@ -27,6 +27,7 @@ use crate::{
parameter::{ConfigResolvableValue, ContextMode},
types::{Error, FinishReason, Input, Output, RunStats, Stats, StepStats, TotalStats},
},
+ utils::strict_serde::from_reader_strict,
};
fn nanos_to_secs(nanos: u64) -> f64 {
@@ -47,7 +48,7 @@ struct RunContext {
pub struct ChatSession {
pub model_path: PathBuf,
- pub model_metadata: ModelMetadata,
+ pub model_metadata: ModelMetadata<LanguageModelConfig>,
tokenizer: Tokenizer,
stop_token_ids: Vec<i32>,
@@ -83,23 +84,16 @@ impl ChatSession {
return Err(Error::UnableToLoadConfig);
}
let config_file = File::open(&config_path).map_err(|_| Error::UnableToLoadConfig)?;
- let model_metadata: ModelMetadata = serde_json::from_reader(BufReader::new(config_file)).map_err(|err| {
- eprintln!("Failed to parse config.json: {err}");
- Error::UnableToLoadConfig
- })?;
-
- let (has_non_attention_mixer, has_mamba_mixer) = model_metadata
- .model_config
- .as_language_model()
- .and_then(|lm| lm.decoder_config().ok())
- .and_then(|dc| dc.layer_configs)
- .map(|layers| {
- let has_non_attention =
- layers.iter().any(|layer| !matches!(layer.mixer_config, MixerConfig::Attention(_)));
- let has_mamba = layers.iter().any(|layer| matches!(layer.mixer_config, MixerConfig::Mamba(_)));
- (has_non_attention, has_mamba)
- })
- .unwrap_or((false, false));
+ let model_metadata: ModelMetadata<LanguageModelConfig> = from_reader_strict(BufReader::new(config_file))
+ .map_err(|err| {
+ eprintln!("Failed to parse config.json: {err}");
+ Error::UnableToLoadConfig
+ })?;
+
+ let layers = &model_metadata.model_config.model_config.transformer_config.layer_configs;
+ let has_non_attention_mixer =
+ layers.iter().any(|layer| !matches!(layer.mixer_config, MixerConfig::Attention(_)));
+ let has_mamba_mixer = layers.iter().any(|layer| matches!(layer.mixer_config, MixerConfig::Mamba(_)));
if has_non_attention_mixer {
match decoding_config.context_mode {
ContextMode::None => {},
@@ -118,8 +112,6 @@ impl ChatSession {
return Err(Error::UnsupportedSpeculatorConfigForModel);
}
- let language_model_config = model_metadata.model_config.as_language_model().ok_or(Error::UnableToLoadConfig)?;
-
let tokenizer_path = model_path.join("tokenizer.json");
if !tokenizer_path.exists() {
return Err(Error::UnableToLoadTokenizer);
@@ -127,12 +119,12 @@ impl ChatSession {
let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(|_| Error::UnableToLoadTokenizer)?;
let stop_token_ids: Vec<i32> =
- language_model_config.generation_config.stop_token_ids.iter().map(|&x| x as i32).collect();
+ model_metadata.model_config.generation_config.stop_token_ids.iter().map(|&x| x as i32).collect();
- let input_processor = InputProcessorDefault::new(language_model_config.message_processor_config.clone());
+ let input_processor = InputProcessorDefault::new(model_metadata.model_config.message_processor_config.clone());
let output_parser =
- OutputParser::new(language_model_config.message_processor_config.output_parser_regex.clone())?;
+ OutputParser::new(model_metadata.model_config.message_processor_config.output_parser_regex.clone())?;
let llm = Box::new(
LanguageModelGenerator::<B>::new(&model_path, decoding_config.clone(), &model_metadata)
@@ -239,11 +231,8 @@ impl ChatSession {
.map(|&id| id as u64)
.collect();
- let language_model_config =
- self.model_metadata.model_config.as_language_model().ok_or(Error::UnableToLoadConfig)?;
-
let language_model_generator = self.llm.as_mut().ok_or(Error::LanguageModelGeneratorNotLoaded)?;
- let context_length = self.decoding_config.context_length.resolve(language_model_config);
+ let context_length = self.decoding_config.context_length.resolve(&self.model_metadata.model_config);
if tokens.len() >= context_length {
return Err(Error::ContextLengthExceeded);
}
@@ -252,9 +241,9 @@ impl ChatSession {
let prefix_len_before = prefix_offset;
let eos_tokens: Vec<u64> =
- language_model_config.generation_config.stop_token_ids.iter().map(|&x| x as u64).collect();
+ self.model_metadata.model_config.generation_config.stop_token_ids.iter().map(|&x| x as u64).collect();
- let sampling_method = config.sampling_policy.resolve(language_model_config);
+ let sampling_method = config.sampling_policy.resolve(&self.model_metadata.model_config);
let mut compiled_grammar: Option<Box<dyn CompiledGrammar>> = if let Some(ref config) = config.grammar_config {
Some(create_compiled_grammar(config, &self.tokenizer, Some(&self.stop_token_ids))?)
@@ -273,9 +262,8 @@ impl ChatSession {
)?;
let prefill_tokens = prefill_result.tokens.clone();
let prefill_duration = prefill_start.elapsed().as_secs_f64();
- language_model_generator.clear_cache();
- let prefill_suffix_length = self.decoding_config.prefill_step_size.resolve(language_model_config);
+ let prefill_suffix_length = self.decoding_config.prefill_step_size.resolve(&self.model_metadata.model_config);
let run_context = RunContext {
eos_tokens,
@@ -345,7 +333,6 @@ impl ChatSession {
)?
};
- language_model_generator.clear_cache();
Ok(generate_output.clone_with_duration(run_start.elapsed().as_secs_f64()))
}
diff --git a/crates/backend-uzu/src/session/classification_session.rs b/crates/backend-uzu/src/session/classification_session.rs
index fd243f4dd..b3711ad93 100644
--- a/crates/backend-uzu/src/session/classification_session.rs
+++ b/crates/backend-uzu/src/session/classification_session.rs
@@ -5,11 +5,12 @@ use tokenizers::Tokenizer;
use crate::{
backends::{common::Backend, select_backend},
classifier::{ClassificationOutput, Classifier, ClassifierTrait},
- config::ModelMetadata,
+ config::{ClassifierModelConfig, ModelMetadata},
session::{
helpers::{InputProcessor, InputProcessorDefault},
types::{Error, Input},
},
+ utils::strict_serde::from_reader_strict,
};
pub struct ClassificationSession {
@@ -30,8 +31,8 @@ impl ClassificationSession {
}
let config_file = std::fs::File::open(&config_path).map_err(|_| Error::UnableToLoadConfig)?;
- let model_metadata: ModelMetadata =
- serde_json::from_reader(std::io::BufReader::new(config_file)).map_err(|_| Error::UnableToLoadConfig)?;
+ let model_metadata: ModelMetadata<ClassifierModelConfig> =
+ from_reader_strict(std::io::BufReader::new(config_file)).map_err(|_| Error::UnableToLoadConfig)?;
let tokenizer_path = model_path.join("tokenizer.json");
if !tokenizer_path.exists() {
@@ -39,9 +40,8 @@ impl ClassificationSession {
}
let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(|_| Error::UnableToLoadTokenizer)?;
- let classifier_model_config = model_metadata.model_config.as_classifier().ok_or(Error::UnableToLoadConfig)?;
let input_processor =
- Box::new(InputProcessorDefault::new(classifier_model_config.message_processor_config.clone()))
+ Box::new(InputProcessorDefault::new(model_metadata.model_config.message_processor_config.clone()))
as Box<dyn InputProcessor>;
let classifier = Box::new(Classifier::<B>::new(&model_path, &model_metadata)?);
diff --git a/crates/backend-uzu/src/session/config/mod.rs b/crates/backend-uzu/src/session/config/mod.rs
index 877a6e691..b2142ca27 100644
--- a/crates/backend-uzu/src/session/config/mod.rs
+++ b/crates/backend-uzu/src/session/config/mod.rs
@@ -9,7 +9,7 @@ pub use decoding_config::DecodingConfig;
pub use grammar_config::GrammarConfig;
pub use run_config::RunConfig;
pub use speculator_config::SpeculatorConfig;
-pub use tts_run_config::{TtsChunkPolicy, TtsNonStreamingMode, TtsPerformanceConfig, TtsRunConfig, TtsRunConfigError};
+pub use tts_run_config::{TtsChunkPolicy, TtsNonStreamingMode, TtsRunConfig, TtsRunConfigError};
#[cfg(metal_backend)]
pub use tts_session_options::TtsSessionOptions;
pub use tts_session_options::{TextDecoderRuntimeConfig, TextSamplingConfig};
diff --git a/crates/backend-uzu/src/session/config/tts_run_config.rs b/crates/backend-uzu/src/session/config/tts_run_config.rs
index 16453a895..d8c7780c6 100644
--- a/crates/backend-uzu/src/session/config/tts_run_config.rs
+++ b/crates/backend-uzu/src/session/config/tts_run_config.rs
@@ -107,36 +107,9 @@ impl Default for TtsRunConfig {
}
}
-#[derive(Debug, Clone, PartialEq)]
-pub struct TtsPerformanceConfig {
- pub streaming: TtsRunConfig,
- pub non_streaming: TtsRunConfig,
- pub non_streaming_chunked_threshold_frames: usize,
-}
-
-impl Default for TtsPerformanceConfig {
- fn default() -> Self {
- let streaming = TtsRunConfig::default();
- let non_streaming = TtsRunConfig {
- streaming_enabled: false,
- chunk_policy: TtsChunkPolicy::Fixed,
- non_streaming_mode: TtsNonStreamingMode::ChunkedIfNeeded,
- initial_chunk_frames: 128,
- min_chunk_frames: 128,
- max_chunk_frames: 128,
- ..TtsRunConfig::default()
- };
- Self {
- streaming,
- non_streaming,
- non_streaming_chunked_threshold_frames: 4096,
- }
- }
-}
-
#[cfg(test)]
mod tests {
- use super::{TtsChunkPolicy, TtsNonStreamingMode, TtsPerformanceConfig, TtsRunConfig};
+ use super::{TtsChunkPolicy, TtsNonStreamingMode, TtsRunConfig};
#[test]
fn default_run_config_matches_production_defaults() {
@@ -210,13 +183,4 @@ mod tests {
};
assert!(invalid.validate_stream_decode().is_err());
}
-
- #[test]
- fn performance_config_defaults_are_consistent() {
- let config = TtsPerformanceConfig::default();
- assert_eq!(config.streaming.chunk_policy, TtsChunkPolicy::Adaptive);
- assert_eq!(config.non_streaming.chunk_policy, TtsChunkPolicy::Fixed);
- assert_eq!(config.non_streaming.min_chunk_frames, config.non_streaming.max_chunk_frames);
- assert_eq!(config.non_streaming.non_streaming_mode, TtsNonStreamingMode::ChunkedIfNeeded);
- }
}
diff --git a/crates/backend-uzu/src/session/parameter/context_length.rs b/crates/backend-uzu/src/session/parameter/context_length.rs
index bdee47a44..017e0d363 100644
--- a/crates/backend-uzu/src/session/parameter/context_length.rs
+++ b/crates/backend-uzu/src/session/parameter/context_length.rs
@@ -18,10 +18,7 @@ impl ConfigResolvableValue<LanguageModelConfig, usize> for ContextLength {
&self,
config: &LanguageModelConfig,
) -> usize {
- let model_context_length = config
- .decoder_config()
- .map(|dc| dc.context_length)
- .unwrap_or(config.model_config.transformer_config.context_length);
+ let model_context_length = config.model_config.transformer_config.context_length;
let proposed_value = match self {
ContextLength::Default => {
if cfg!(target_os = "ios") {
diff --git a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs b/crates/backend-uzu/src/session/parameter/prefill_step_size.rs
index 235f14076..6bd145fda 100644
--- a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs
+++ b/crates/backend-uzu/src/session/parameter/prefill_step_size.rs
@@ -34,14 +34,11 @@ impl ConfigResolvableValue<LanguageModelConfig, usize> for PrefillStepSize {
let model_context_length = config.model_config.transformer_config.context_length;
let minimal_sliding_window_size = config
- .decoder_config()
- .ok()
- .and_then(|dc| dc.sliding_window_sizes)
- .as_deref()
- .into_iter()
- .flatten()
- .flatten()
- .copied()
+ .model_config
+ .transformer_config
+ .layer_configs
+ .iter()
+ .filter_map(|l| l.mixer_config.sliding_window_size())
.min()
.unwrap_or(usize::MAX);
diff --git a/crates/backend-uzu/src/session/tts_session.rs b/crates/backend-uzu/src/session/tts_session.rs
index b536d3411..6a4198e3a 100644
--- a/crates/backend-uzu/src/session/tts_session.rs
+++ b/crates/backend-uzu/src/session/tts_session.rs
@@ -37,8 +37,8 @@ use crate::{
matmul::{MatmulArgumentC, MatmulArguments, MatmulKernel},
},
},
- config::{InnerModelConfig, ModelMetadata, TtsMessageProcessorConfig},
- encodable_block::{Decoder, EncodingParameters, Sampling as GpuSampling},
+ config::{ModelMetadata, TtsMessageProcessorConfig, TtsModelConfig},
+ encodable_block::{Decoder, Sampling as GpuSampling},
forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape, state::SharedBuffers},
parameters::ParameterLoader,
session::{
diff --git a/crates/backend-uzu/src/session/tts_session/backend_factory.rs b/crates/backend-uzu/src/session/tts_session/backend_factory.rs
index 82b2f11fe..0302a2015 100644
--- a/crates/backend-uzu/src/session/tts_session/backend_factory.rs
+++ b/crates/backend-uzu/src/session/tts_session/backend_factory.rs
@@ -19,7 +19,7 @@ pub(super) fn build_audio_decoder_backend<B: Backend + Send + Sync>(
pub(super) fn load_tts_runtime<B: Backend + Send + Sync>(
model_path: &Path,
- model_metadata: &ModelMetadata,
+ model_metadata: &ModelMetadata<TtsModelConfig>,
options: &TtsSessionOptions,
) -> Result<LoadedTtsRuntime<B>, Error> {
if model_metadata.model_type != ModelType::TtsModel {
@@ -30,13 +30,11 @@ pub(super) fn load_tts_runtime<B: Backend + Send + Sync>(
.into());
}
- let tts_model_config =
- model_metadata.model_config.as_tts().ok_or(TtsModelConfigError::MissingTtsModelConfig)?.clone();
let audio: AudioGenerationContext<B> =
- tts_model_config.create_audio_generation_context_with_model_path(model_path)?;
- let text_decoder = build_text_decoder_backend(&tts_model_config, &audio, model_path, options)?;
+ model_metadata.model_config.create_audio_generation_context_with_model_path(model_path)?;
+ let text_decoder = build_text_decoder_backend(&model_metadata.model_config, &audio, model_path, options)?;
let audio_decoder = build_audio_decoder_backend(&audio)?;
- let message_processor_config = tts_model_config.message_processor_config.clone();
+ let message_processor_config = model_metadata.model_config.message_processor_config.clone();
Ok(LoadedTtsRuntime {
audio,
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
index c35872969..9ce351393 100644
--- a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
+++ b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
@@ -91,7 +91,8 @@ impl<B: Backend> TokenDecoderContext<B> {
runtime_config: &TextDecoderRuntimeConfig,
) -> Result<(Self, DataType), Error> {
let model_shape = ModelShape::from_decoder_config(&decoder_config);
- let max_suffix_length = text_decoder_prefill_step_size(runtime_config, decoder_config.context_length).max(32);
+ let max_suffix_length =
+ text_decoder_prefill_step_size(runtime_config, decoder_config.transformer_config.context_length).max(32);
let max_prefix_length = max_suffix_length;
let activation_data_type = model_shape.activation_data_type();
let loaded_model = TokenDecoderLoadedModel::<B>::load(
@@ -112,7 +113,8 @@ impl<B: Backend> TokenDecoderContext<B> {
max_prefix_length,
max_suffix_length,
)));
- let intermediate_data_type: DataType = decoder_config.output_norm_config.scale_precision.into();
+ let intermediate_data_type: DataType =
+ decoder_config.transformer_config.output_norm_config.scale_precision.into();
let kv_cache_update = KVCacheUpdate::new(context.as_ref(), intermediate_data_type, max_prefix_length)
.map_err(unable_to_create_context)?;
@@ -207,7 +209,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
runtime_config,
)?;
let context: Rc<B::Context> = Rc::clone(ctx.context());
- let model_dim = ctx.decoder_config.model_dim;
+ let model_dim = ctx.decoder_config.transformer_config.model_dim;
let tensor_add_scale =
<B::Kernels as Kernels>::TensorAddScaleKernel::new(context.as_ref(), activation_data_type)
.map_err(unable_to_create_context)?;
@@ -336,7 +338,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
&mut self,
max_prefix_length: usize,
) -> Result<(), Error> {
- let max_prefix_length = max_prefix_length.max(1).min(self.ctx.decoder_config.context_length);
+ let max_prefix_length = max_prefix_length.max(1).min(self.ctx.decoder_config.transformer_config.context_length);
let max_suffix_length = text_decoder_prefill_step_size(&self.ctx.runtime_config, max_prefix_length).max(32);
if self.ctx.current_max_prefix_length == max_prefix_length {
return Ok(());
@@ -344,7 +346,8 @@ impl<B: Backend> TokenDecoderRunner<B> {
let context = self.ctx.context.as_ref();
*self.ctx.cache_layers.borrow_mut() =
CacheLayers::new(context, &self.ctx.model_shape, max_prefix_length, max_suffix_length);
- let intermediate_data_type: DataType = self.ctx.decoder_config.output_norm_config.scale_precision.into();
+ let intermediate_data_type: DataType =
+ self.ctx.decoder_config.transformer_config.output_norm_config.scale_precision.into();
self.ctx.kv_cache_update =
KVCacheUpdate::new(context, intermediate_data_type, max_prefix_length).map_err(unable_to_create_context)?;
self.ctx.current_max_prefix_length = max_prefix_length;
@@ -365,8 +368,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
let positions: Vec<usize> = (self.next_position..self.next_position + token_count).collect();
let token_inputs = self.llm_token_inputs(token_ids, &positions, None, None, 0, 0);
- let encoding_parameters = EncodingParameters::new();
-
let context = Rc::clone(&self.ctx.context);
let mut encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
@@ -376,7 +377,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
.encode_prefill(
self.decoder_arguments(&token_inputs, token_count, 0, 0, &mut *cache_layers),
token_inputs.token_ids(),
- &encoding_parameters,
&mut encoder,
)
.map_err(|err| Error::EncodeFailed(Box::new(err)))?;
@@ -562,7 +562,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<(), Error> {
- let encoding_parameters = EncodingParameters::new();
let cache_layers_rc = self.ctx.cache_layers.clone();
let token_bitmask =
vocab_mask_limit.and_then(|limit| self.get_single_token_vocab_mask(limit)).map(Box::<[u32]>::from);
@@ -587,7 +586,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
self.decoder_arguments(&token_inputs, 1, 0, 1, &mut *cache_layers),
DecoderDecodeInput::TokenIds(token_inputs.token_ids()),
None,
- &encoding_parameters,
encoder,
)
.map_err(|err| Error::EncodeFailed(Box::new(err)))?
@@ -776,7 +774,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
pending_token_inputs.push(token_inputs);
let token_inputs = pending_token_inputs.last().expect("token inputs must be pending");
- let encoding_parameters = EncodingParameters::new();
let mut main = self
.ctx
.executables
@@ -816,13 +813,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
let hidden_capture = capture_hidden.then_some(&mut self.single_hidden_capture);
self.ctx
.executables
- .encode_decode(
- decoder_arguments,
- DecoderDecodeInput::Embeddings(main),
- hidden_capture,
- &encoding_parameters,
- encoder,
- )
+ .encode_decode(decoder_arguments, DecoderDecodeInput::Embeddings(main), hidden_capture, encoder)
.map_err(|err| Error::EncodeFailed(Box::new(err)))?
};
let mut sampling_output = self.create_sampling_output(sampling_length);
@@ -1000,7 +991,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
main: &mut Allocation<B>,
override_embedding: &Allocation<B>,
) -> Result<(), Error> {
- let model_dim = self.ctx.decoder_config.model_dim;
+ let model_dim = self.ctx.decoder_config.transformer_config.model_dim;
let model_dim_bytes = model_dim.checked_mul(self.activation_data_type().size_in_bytes()).ok_or(
TtsModelConfigError::ModelDimExceedsU32 {
model_dim,
@@ -1020,7 +1011,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
if token_count == 0 {
return Err(Error::GenerateFailed);
}
- let model_dim = self.ctx.decoder_config.model_dim;
+ let model_dim = self.ctx.decoder_config.transformer_config.model_dim;
let model_dim_u32 = u32::try_from(model_dim).map_err(|_| TtsModelConfigError::ModelDimExceedsU32 {
model_dim,
})?;
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_support.rs b/crates/backend-uzu/src/session/tts_session/decoder_support.rs
index 68cdb2653..a04ccb40c 100644
--- a/crates/backend-uzu/src/session/tts_session/decoder_support.rs
+++ b/crates/backend-uzu/src/session/tts_session/decoder_support.rs
@@ -445,7 +445,7 @@ impl<B: Backend + Send + Sync> TtsSession<B> {
return Err(Error::UnableToLoadConfig);
}
let config_file = File::open(&config_path).map_err(|_| Error::UnableToLoadConfig)?;
- let model_metadata: ModelMetadata =
+ let model_metadata: ModelMetadata<TtsModelConfig> =
serde_json::from_reader(std::io::BufReader::new(config_file)).map_err(|_| Error::UnableToLoadConfig)?;
Self::from_model_metadata_with_options(model_path, model_metadata, options)
@@ -461,7 +461,7 @@ impl<B: Backend + Send + Sync> TtsSession<B> {
fn from_model_metadata_with_options(
model_path: PathBuf,
- model_metadata: ModelMetadata,
+ model_metadata: ModelMetadata<TtsModelConfig>,
options: TtsSessionOptions,
) -> Result<Self, Error> {
let tokenizer_path = model_path.join("tokenizer.json");
diff --git a/crates/backend-uzu/src/session/tts_session/fishaudio.rs b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
index ef1b5dc55..108248bc4 100644
--- a/crates/backend-uzu/src/session/tts_session/fishaudio.rs
+++ b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
@@ -6,7 +6,7 @@ use super::*;
use crate::{
array::ArrayContextExt,
backends::common::{Allocation, AsBufferRangeRef, DenseBuffer},
- config::TtsMessageProcessorConfig,
+ config::{DecoderConfig, TtsMessageProcessorConfig},
encodable_block::SamplingInputs,
forward_pass::token_inputs::TokenInputs,
session::types::{TtsModelConfigError, TtsPromptConfigError},
@@ -262,19 +262,18 @@ pub(super) fn build_fishaudio_text_decoder_runtime<B: Backend>(
let slow_transformer_config = config.slow_model_config.clone();
let fast_transformer_config = config.fast_model_config.clone();
- let slow_inner_config = InnerModelConfig {
+ let slow_decoder_config = Rc::new(DecoderConfig {
embedding_config: config.slow_embeddings_config.to_text_decoder_embedding_config(),
transformer_config: slow_transformer_config,
vocab_size: config.vocab_size,
- };
- let fast_inner_config = InnerModelConfig {
+ pard_token: None,
+ });
+ let fast_decoder_config = Rc::new(DecoderConfig {
embedding_config: config.fast_embeddings_config.to_text_decoder_embedding_config(),
transformer_config: fast_transformer_config,
vocab_size: config.codebook_size,
- };
-
- let slow_decoder_config = Rc::new(slow_inner_config.to_decoder_config().map_err(|_| Error::UnableToLoadConfig)?);
- let fast_decoder_config = Rc::new(fast_inner_config.to_decoder_config().map_err(|_| Error::UnableToLoadConfig)?);
+ pard_token: None,
+ });
let text_decoder_context = B::Context::new().map_err(unable_to_create_context)?;
let slow_runner = TokenDecoderRunner::new_with_context(
diff --git a/crates/backend-uzu/src/session/types/message.rs b/crates/backend-uzu/src/session/types/message.rs
index 6f4afd26c..c59d6e437 100644
--- a/crates/backend-uzu/src/session/types/message.rs
+++ b/crates/backend-uzu/src/session/types/message.rs
@@ -2,12 +2,16 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
+#[cfg(metal_backend)]
+use crate::config::TtsMessageProcessorConfig;
use crate::{
- config::{MessageProcessorConfig, TtsMessageProcessorConfig},
+ config::MessageProcessorConfig,
session::{parameter::ConfigResolvableValue, types::Role},
};
+#[cfg(metal_backend)]
pub(crate) const DEFAULT_TTS_SPEAKER_ID: &str = "speaker:0";
+#[cfg(metal_backend)]
pub(crate) const DEFAULT_TTS_STYLE: &str = "interleave";
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -65,6 +69,7 @@ impl ConfigResolvableValue<MessageProcessorConfig, HashMap<String, String>> for
}
}
+#[cfg(metal_backend)]
impl ConfigResolvableValue<TtsMessageProcessorConfig, HashMap<String, String>> for Message {
fn resolve(
&self,
diff --git a/crates/backend-uzu/src/tracer/trace_validator.rs b/crates/backend-uzu/src/tracer/trace_validator.rs
index 43f8a3bea..c6b1eda58 100644
--- a/crates/backend-uzu/src/tracer/trace_validator.rs
+++ b/crates/backend-uzu/src/tracer/trace_validator.rs
@@ -20,8 +20,8 @@ use crate::{
array::Array,
backends::common::{Allocation, Backend, Encoder, kernel::kv_cache_update::KVCacheUpdate},
classifier::Classifier,
- config::ModelMetadata,
- encodable_block::{DecoderDecodeInput, EncodingParameters, Sampling},
+ config::{ClassifierModelConfig, LanguageModelConfig, ModelMetadata, ModelType},
+ encodable_block::{DecoderDecodeInput, Sampling},
forward_pass::{cache_layers::CacheLayers, token_inputs::TokenInputs, traces::ActivationTrace},
language_model::{
language_model_generator_context::LanguageModelGeneratorContext,
@@ -176,26 +176,35 @@ impl<B: Backend> TraceValidator<B> {
}
let config_file = File::open(&config_path).map_err(|_| Error::UnableToLoadConfig)?;
- let metadata: ModelMetadata =
+ let raw_metadata: ModelMetadata<serde_json::Value> =
serde_json::from_reader(std::io::BufReader::new(config_file)).map_err(|_| Error::UnableToLoadConfig)?;
- let context = if metadata.model_config.is_classifier() {
- let classifier = Classifier::new(model_path, &metadata)?;
- ModelContext::Classifier(classifier)
- } else {
- let prefill_step_size = Self::determine_prefill_step_size(model_path);
- let decoding_config = DecodingConfig::new(
- ContextMode::default(),
- ContextLength::default(),
- PrefillStepSize::Custom(prefill_step_size),
- SpeculatorConfig::default(),
- SamplingSeed::default(),
- AsyncBatchSize::default(),
- );
- let mut llm_context = LanguageModelGeneratorContext::new(model_path, &decoding_config, &metadata)?;
- let desired_suffix_length = prefill_step_size.max(decoding_config.generate_suffix_length());
- Self::ensure_llm_context_capacity(&decoding_config, desired_suffix_length, &mut llm_context);
- ModelContext::LanguageModelGenerator(llm_context)
+ let context = match raw_metadata.model_type {
+ ModelType::ClassifierModel => {
+ let metadata: ModelMetadata<ClassifierModelConfig> =
+ serde_json::from_value(serde_json::to_value(&raw_metadata).map_err(|_| Error::UnableToLoadConfig)?)
+ .map_err(|_| Error::UnableToLoadConfig)?;
+ ModelContext::Classifier(Classifier::new(model_path, &metadata)?)
+ },
+ ModelType::LanguageModel => {
+ let metadata: ModelMetadata<LanguageModelConfig> =
+ serde_json::from_value(serde_json::to_value(&raw_metadata).map_err(|_| Error::UnableToLoadConfig)?)
+ .map_err(|_| Error::UnableToLoadConfig)?;
+ let prefill_step_size = Self::determine_prefill_step_size(model_path);
+ let decoding_config = DecodingConfig::new(
+ ContextMode::default(),
+ ContextLength::default(),
+ PrefillStepSize::Custom(prefill_step_size),
+ SpeculatorConfig::default(),
+ SamplingSeed::default(),
+ AsyncBatchSize::default(),
+ );
+ let mut llm_context = LanguageModelGeneratorContext::new(model_path, &decoding_config, &metadata)?;
+ let desired_suffix_length = prefill_step_size.max(decoding_config.generate_suffix_length());
+ Self::ensure_llm_context_capacity(&decoding_config, desired_suffix_length, &mut llm_context);
+ ModelContext::LanguageModelGenerator(llm_context)
+ },
+ ModelType::TtsModel => return Err(Error::UnableToLoadConfig),
};
Ok(Self {
@@ -217,14 +226,6 @@ impl<B: Backend> TraceValidator<B> {
}
}
- pub fn is_classifier(&self) -> bool {
- matches!(self.context, ModelContext::Classifier(_))
- }
-
- pub fn is_language_model_generator(&self) -> bool {
- matches!(self.context, ModelContext::LanguageModelGenerator(_))
- }
-
// ========================================================================
// LLM Validation
// ========================================================================
@@ -272,7 +273,6 @@ impl<B: Backend> TraceValidator<B> {
decoder_arguments,
DecoderDecodeInput::TokenIds(token_inputs.token_ids()),
None,
- &EncodingParameters::new(),
&mut encoder,
)
.map_err(|e| Error::EncodeFailed(Box::new(e)))?;
@@ -935,8 +935,8 @@ impl<B: Backend> TraceValidator<B> {
desired_suffix_length,
)));
- let decoder_config = context.model_config.decoder_config().expect("Failed to resolve decoder config");
- let intermediate_dtype: DataType = decoder_config.output_norm_config.scale_precision.into();
+ let intermediate_dtype: DataType =
+ context.model_config.model_config.transformer_config.output_norm_config.scale_precision.into();
context.kv_cache_update = Box::new(
KVCacheUpdate::new(context.context.as_ref(), intermediate_dtype, resolved_prefix_length)
diff --git a/crates/backend-uzu/src/utils/mod.rs b/crates/backend-uzu/src/utils/mod.rs
index 56db3575d..74b765864 100644
--- a/crates/backend-uzu/src/utils/mod.rs
+++ b/crates/backend-uzu/src/utils/mod.rs
@@ -4,6 +4,7 @@ pub mod memory;
#[cfg(metal_backend)]
pub mod model_size;
pub mod pointers;
+pub mod strict_serde;
pub mod version;
pub use version::{TOOLCHAIN_VERSION, VERSION};
diff --git a/crates/backend-uzu/src/utils/strict_serde.rs b/crates/backend-uzu/src/utils/strict_serde.rs
new file mode 100644
index 000000000..5023edb16
--- /dev/null
+++ b/crates/backend-uzu/src/utils/strict_serde.rs
@@ -0,0 +1,14 @@
+use std::io::Read;
+
+use serde::de::{DeserializeOwned, Error as _};
+
+pub fn from_reader_strict<T: DeserializeOwned>(reader: impl Read) -> Result<T, serde_json::Error> {
+ let value: serde_json::Value = serde_json::from_reader(reader)?;
+ let mut unknown: Vec<String> = Vec::new();
+ let parsed = serde_ignored::deserialize(value, |path| unknown.push(path.to_string()))?;
+ if unknown.is_empty() {
+ Ok(parsed)
+ } else {
+ Err(serde_json::Error::custom(format!("unknown config fields: {}", unknown.join(", "))))
+ }
+}
diff --git a/crates/backend-uzu/tests/unit/config/attention_test.rs b/crates/backend-uzu/tests/unit/config/attention_test.rs
deleted file mode 100644
index f25a930d1..000000000
--- a/crates/backend-uzu/tests/unit/config/attention_test.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use serde_json5::from_str;
-
-use super::{
- super::{common::ConfigDataType, linear::QuantizationConfig},
- *,
-};
-use crate::backends::common::gpu_types::QuantizationMode;
-
-#[test]
-fn test_attention_config() {
- let config_str = r#"
- {
- "qkv_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0,
- },
- "out_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0,
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 12,
- "num_groups": 12,
- "head_dim": 64,
- "is_causal": false,
- "scale": null,
- "sliding_window_size": null,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- }
- "#;
-
- let ground_truth_config = AttentionConfig {
- qkv_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- out_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- query_norm_config: None,
- key_norm_config: None,
- num_heads: Some(12),
- num_groups: Some(12),
- head_dim: Some(64),
- is_causal: Some(false),
- scale: None,
- sliding_window_size: None,
- logit_soft_cap: None,
- has_sinks: false,
- has_qkv_biases: false,
- has_out_biases: false,
- has_gate: false,
- gate_projection_config: None,
- use_rope: true,
- partial_rope_dim: None,
- };
-
- let deserialized_config: AttentionConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/decoder_layer_test.rs b/crates/backend-uzu/tests/unit/config/decoder_layer_test.rs
deleted file mode 100644
index f96f51681..000000000
--- a/crates/backend-uzu/tests/unit/config/decoder_layer_test.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-use serde_json::from_str;
-
-use super::{
- super::{
- common::ConfigDataType,
- linear::{LinearConfig, QuantizationConfig},
- normalization::UpcastMode,
- },
- *,
-};
-use crate::{
- backends::common::{ActivationConfig, gpu_types::QuantizationMode},
- config::mlp,
-};
-
-#[test]
-fn test_decoder_layer_config() {
- let config_str = r#"
- {
- "pre_attention_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "out_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 12,
- "num_groups": 12,
- "head_dim": 64,
- "is_causal": true,
- "scale": null,
- "sliding_window_size": null,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- },
- "post_attention_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"}
- },
- "post_mlp_norm_config": null
- }
- "#;
-
- let ground_truth_config = DecoderLayerConfig {
- pre_attention_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- pre_mlp_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- mixer_config: MixerConfig::Attention(AttentionConfig {
- qkv_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- out_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- query_norm_config: None,
- key_norm_config: None,
- num_heads: Some(12),
- num_groups: Some(12),
- head_dim: Some(64),
- is_causal: Some(true),
- scale: None,
- sliding_window_size: None,
- logit_soft_cap: None,
- has_sinks: false,
- has_qkv_biases: false,
- has_out_biases: false,
- has_gate: false,
- gate_projection_config: None,
- use_rope: true,
- partial_rope_dim: None,
- }),
- mlp_config: MLPConfig::Dense(mlp::DenseMLPConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: false,
- has_down_biases: false,
- gate_clipping: None,
- up_clipping: None,
- activation_to_gate: true,
- }),
- post_attention_norm_config: None,
- post_mlp_norm_config: None,
- };
-
- let deserialized_config: DecoderLayerConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/decoder_test.rs b/crates/backend-uzu/tests/unit/config/decoder_test.rs
deleted file mode 100644
index 1c8c713e3..000000000
--- a/crates/backend-uzu/tests/unit/config/decoder_test.rs
+++ /dev/null
@@ -1,399 +0,0 @@
-use serde_json5::from_str;
-
-use super::{
- super::{
- attention::AttentionConfig,
- common::ConfigDataType,
- embedding::{EmbeddingConfig, EmbeddingConfigCommon},
- linear::{LinearConfig, QuantizationConfig},
- mlp::{DenseMLPConfig, MLPConfig},
- normalization::UpcastMode,
- rope::RopeConfigCommon,
- },
- *,
-};
-use crate::backends::common::{ActivationConfig, gpu_types::QuantizationMode};
-
-#[test]
-fn test_decoder_config() {
- let config_str = r#"
- {
- "embedding_config": {
- "type": "MLXQuantizedTiedEmbeddingConfig",
- "input_scale": null,
- "logit_soft_cap": null,
- "group_size": 128,
- "embedding_quantization_mode": "int8",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16"
- },
- "global_rope_config": {
- "type": "LlamaRoPEConfig",
- "precision": "bfloat16",
- "base": 500000.0,
- "max_sequence_length": 262144,
- "scaling_factor": 32.0,
- "original_context_length": 8192,
- "low_frequency_factor": 1.0,
- "high_frequency_factor": 4.0
- },
- "local_rope_config": null,
- "layer_config": {
- "pre_attention_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "out_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 12,
- "num_groups": 12,
- "head_dim": 64,
- "is_causal": true,
- "scale": null,
- "sliding_window_size": null,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- },
- "post_attention_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"}
- },
- "post_mlp_norm_config": null
- },
- "output_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- },
- "vocab_size": 128256,
- "model_dim": 2048,
- "hidden_dim": 8192,
- "num_heads": 32,
- "num_groups": 8,
- "head_dim": 64,
- "attention_scale": null,
- "num_layers": 16,
- "sliding_window_sizes": null,
- "context_length": 8192
- }
- "#;
-
- let ground_truth_config = DecoderConfig {
- embedding_config: EmbeddingConfig::MLXQuantizedTied {
- common: EmbeddingConfigCommon {
- input_scale: None,
- logit_soft_cap: None,
- },
- group_size: 128,
- embedding_quantization_mode: QuantizationMode::INT8,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- global_rope_config: Some(RoPEConfig::Llama {
- common: RopeConfigCommon {
- precision: ConfigDataType::BFloat16,
- base: 500000.0,
- max_sequence_length: 262144,
- },
- scaling_factor: 32.0,
- original_context_length: 8192,
- low_frequency_factor: 1.0,
- high_frequency_factor: 4.0,
- }),
- local_rope_config: None,
- layer_config: DecoderLayerConfig {
- pre_attention_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- pre_mlp_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- mixer_config: MixerConfig::Attention(AttentionConfig {
- qkv_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- out_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- query_norm_config: None,
- key_norm_config: None,
- num_heads: Some(12),
- num_groups: Some(12),
- head_dim: Some(64),
- is_causal: Some(true),
- scale: None,
- sliding_window_size: None,
- logit_soft_cap: None,
- has_sinks: false,
- has_qkv_biases: false,
- has_out_biases: false,
- has_gate: false,
- gate_projection_config: None,
- use_rope: true,
- partial_rope_dim: None,
- }),
- mlp_config: MLPConfig::Dense(DenseMLPConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: false,
- has_down_biases: false,
- gate_clipping: None,
- up_clipping: None,
- activation_to_gate: true,
- }),
- post_attention_norm_config: None,
- post_mlp_norm_config: None,
- },
- output_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- layer_configs: None,
- vocab_size: 128256,
- model_dim: 2048,
- hidden_dim: 8192,
- num_heads: 32,
- num_groups: 8,
- head_dim: 64,
- attention_scale: None,
- num_layers: 16,
- sliding_window_sizes: None,
- layer_types: None,
- context_length: 8192,
- };
-
- let deserialized_config: DecoderConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
-
-#[test]
-fn test_decoder_config_with_layer_configs() {
- let config_str = r#"
- {
- "embedding_config": {
- "type": "TiedEmbeddingConfig",
- "input_scale": null,
- "logit_soft_cap": null,
- "precision": "bfloat16"
- },
- "global_rope_config": null,
- "local_rope_config": null,
- "layer_configs": [
- {
- "pre_mixer_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "out_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 4,
- "num_groups": 1,
- "head_dim": 256,
- "is_causal": true,
- "scale": 0.0625,
- "sliding_window_size": 512,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- },
- "post_mixer_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "activation": {
- "type": "GELU"
- }
- },
- "post_mlp_norm_config": null
- },
- {
- "pre_mixer_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "out_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 4,
- "num_groups": 1,
- "head_dim": 256,
- "is_causal": true,
- "scale": 0.0625,
- "sliding_window_size": 256,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- },
- "post_mixer_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "activation": {
- "type": "GELU"
- }
- },
- "post_mlp_norm_config": null
- }
- ],
- "output_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "vocab_size": 32000,
- "model_dim": 1152,
- "hidden_dim": 6912,
- "context_length": 32768
- }
- "#;
-
- let config: DecoderConfig = from_str(config_str).unwrap();
- assert_eq!(config.num_layers, 2);
- assert_eq!(config.num_heads, 4);
- assert_eq!(config.num_groups, 1);
- assert_eq!(config.head_dim, 256);
- assert_eq!(config.attention_scale, Some(0.0625));
- let sliding_windows = config.sliding_window_sizes.unwrap();
- assert_eq!(sliding_windows.len(), 2);
- assert_eq!(sliding_windows[0], Some(512));
- assert_eq!(sliding_windows[1], Some(256));
- let layer_types = config.layer_types.unwrap();
- assert!(matches!(layer_types[0], DecoderLayerType::Transformer));
- assert_eq!(config.layer_configs.unwrap().len(), 2);
-}
diff --git a/crates/backend-uzu/tests/unit/config/embedding_test.rs b/crates/backend-uzu/tests/unit/config/embedding_test.rs
deleted file mode 100644
index 85f1af7b0..000000000
--- a/crates/backend-uzu/tests/unit/config/embedding_test.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-use serde_json::from_str;
-
-use super::*;
-
-#[test]
-fn test_embedding_config() {
- let semi_config_str = r#"
- {
- "type": "MLXSemiQuantizedUntiedEmbeddingConfig",
- "input_scale": null,
- "logit_soft_cap": null,
- "group_size": 128,
- "embedding_quantization_mode": "uint4",
- "activation_quantization_mode": null,
- "activation_precision": "bfloat16"
- }
- "#;
-
- let semi_config = EmbeddingConfig::MLXSemiQuantizedUntied {
- common: EmbeddingConfigCommon {
- input_scale: None,
- logit_soft_cap: None,
- },
- group_size: 128,
- embedding_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: None,
- activation_precision: ConfigDataType::BFloat16,
- };
-
- let deserialized: EmbeddingConfig = from_str(semi_config_str).unwrap();
- assert_eq!(deserialized, semi_config);
-
- 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/crates/backend-uzu/tests/unit/config/linear_test.rs b/crates/backend-uzu/tests/unit/config/linear_test.rs
deleted file mode 100644
index 9c3fc37a1..000000000
--- a/crates/backend-uzu/tests/unit/config/linear_test.rs
+++ /dev/null
@@ -1,62 +0,0 @@
-use serde_json5::from_str;
-
-use super::*;
-
-#[test]
-fn test_linear_config() {
- let config_str = r#"
- {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0,
- }
- "#;
-
- let ground_truth_config = LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- };
-
- let deserialized_config: LinearConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
-
-#[test]
-fn test_rht_linear_wrapper_config() {
- let config_str = r#"
- {
- "type": "RHTLinearWrapperConfig",
- "block_size": 32,
- "inner_config": {
- "type": "GroupQuantizedLinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": null,
- "activation_precision": "bfloat16"
- }
- }
- "#;
-
- let ground_truth_config = LinearConfig::RHTLinearWrapper {
- block_size: 32,
- inner_config: Box::new(LinearConfig::Quantized(QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: None,
- activation_precision: ConfigDataType::BFloat16,
- })),
- };
-
- let deserialized_config: LinearConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/mlp_test.rs b/crates/backend-uzu/tests/unit/config/mlp_test.rs
deleted file mode 100644
index b9254a480..000000000
--- a/crates/backend-uzu/tests/unit/config/mlp_test.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use serde_json::from_str;
-
-use super::{super::linear::QuantizationConfig, *};
-use crate::{backends::common::gpu_types::QuantizationMode, config::ConfigDataType};
-
-#[test]
-fn test_dense_mlp_config() {
- let config_str = r#"
- {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"}
- }
- "#;
-
- let ground_truth_config = MLPConfig::Dense(DenseMLPConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: false,
- has_down_biases: false,
- gate_clipping: None,
- up_clipping: None,
- activation_to_gate: true,
- });
-
- let deserialized_config: MLPConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
-
-#[test]
-fn test_moe_mlp_config() {
- let config_str = r#"
- {
- "type": "MixtureOfExpertsConfig",
- "num_routed_experts": 32,
- "num_active_routed_experts": 4,
- "routing_function": {"type": "SoftmaxRouting"},
- "router_config": {"type": "FullPrecisionLinearConfig", "precision": "bfloat16"},
- "router_has_biases": true,
- "expert_config": {
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"},
- "has_up_biases": true,
- "has_down_biases": true,
- "gate_clipping": [null, 7.0],
- "up_clipping": [-6.0, 8.0]
- }
- }
- "#;
-
- let ground_truth_config = MLPConfig::MixtureOfExperts(MixtureOfExpertsConfig {
- num_routed_experts: 32,
- num_active_routed_experts: 4,
- routing_function: RoutingFunctionConfig::SoftmaxRouting,
- router_config: LinearConfig::FullPrecision {
- precision: ConfigDataType::BFloat16,
- },
- router_has_biases: true,
- expert_config: MoeExpertConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: true,
- has_down_biases: true,
- gate_clipping: [None, Some(7.0)],
- up_clipping: [-6.0, 8.0],
- },
- });
-
- let deserialized_config: MLPConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
-
-#[test]
-fn test_moe_mlp_config_with_additional_fields() {
- let config_str = r#"
- {
- "type": "MixtureOfExpertsConfig",
- "num_routed_experts": 32,
- "num_active_routed_experts": 4,
- "routing_function": {"type": "SoftmaxRouting"},
- "router_config": {"type": "FullPrecisionLinearConfig", "precision": "bfloat16"},
- "router_has_biases": true,
- "num_shared_experts": 0,
- "expert_hidden_dim": 2880,
- "gate_config": null,
- "expert_config": {
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"},
- "has_up_biases": true,
- "has_down_biases": true,
- "gate_clipping": [null, 7.0],
- "up_clipping": [-6.0, 8.0]
- }
- }
- "#;
-
- let ground_truth_config = MLPConfig::MixtureOfExperts(MixtureOfExpertsConfig {
- num_routed_experts: 32,
- num_active_routed_experts: 4,
- routing_function: RoutingFunctionConfig::SoftmaxRouting,
- router_config: LinearConfig::FullPrecision {
- precision: ConfigDataType::BFloat16,
- },
- router_has_biases: true,
- expert_config: MoeExpertConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: true,
- has_down_biases: true,
- gate_clipping: [None, Some(7.0)],
- up_clipping: [-6.0, 8.0],
- },
- });
-
- let deserialized_config: MLPConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/normalization/normalization_config_test.rs b/crates/backend-uzu/tests/unit/config/normalization/normalization_config_test.rs
deleted file mode 100644
index bdced4974..000000000
--- a/crates/backend-uzu/tests/unit/config/normalization/normalization_config_test.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-use serde_json::from_str;
-
-use super::*;
-
-#[test]
-fn test_normalization_config() {
- let config_str = r#"
- {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization"
- }
- "#;
-
- let ground_truth_config = NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-05,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- };
-
- let deserialized_config: NormalizationConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/rope_test.rs b/crates/backend-uzu/tests/unit/config/rope_test.rs
deleted file mode 100644
index 9213b5bfc..000000000
--- a/crates/backend-uzu/tests/unit/config/rope_test.rs
+++ /dev/null
@@ -1,34 +0,0 @@
-use serde_json::from_str;
-
-use super::*;
-
-#[test]
-fn test_rope_config() {
- let config_str = r#"
- {
- "type": "LlamaRoPEConfig",
- "precision": "bfloat16",
- "base": 500000.0,
- "max_sequence_length": 131072,
- "scaling_factor": 32.0,
- "original_context_length": 8192,
- "low_frequency_factor": 1.0,
- "high_frequency_factor": 4.0
- }
- "#;
-
- let ground_truth_config = RoPEConfig::Llama {
- common: RopeConfigCommon {
- precision: ConfigDataType::BFloat16,
- base: 500000.0,
- max_sequence_length: 131072,
- },
- scaling_factor: 32.0,
- original_context_length: 8192,
- low_frequency_factor: 1.0,
- high_frequency_factor: 4.0,
- };
-
- let deserialized_config: RoPEConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/backend-uzu/tests/unit/config/transformer_layer_test.rs b/crates/backend-uzu/tests/unit/config/transformer_layer_test.rs
deleted file mode 100644
index 921b0c3ca..000000000
--- a/crates/backend-uzu/tests/unit/config/transformer_layer_test.rs
+++ /dev/null
@@ -1,175 +0,0 @@
-use serde_json::from_str;
-
-use super::{
- super::{
- attention::AttentionConfig,
- common::ConfigDataType,
- linear::{LinearConfig, QuantizationConfig},
- normalization::UpcastMode,
- },
- *,
-};
-use crate::{
- backends::common::{ActivationConfig, gpu_types::QuantizationMode},
- config::mlp,
-};
-
-#[test]
-fn test_transformer_layer_config() {
- let config_str = r#"
- {
- "pre_attention_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization",
- "subtract_mean": false
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "out_projection_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 12,
- "num_groups": 12,
- "head_dim": 64,
- "is_causal": false,
- "scale": null,
- "sliding_window_size": null,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false,
- "use_rope": true
- },
- "post_attention_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-05,
- "scale_offset": null,
- "upcast_mode": "only_normalization",
- "subtract_mean": false
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "QLoRALinearConfig",
- "group_size": 32,
- "weight_quantization_mode": "uint4",
- "activation_quantization_mode": "int8",
- "activation_precision": "bfloat16",
- "lora_rank": 16,
- "lora_scale": 2.0
- },
- "activation": {"type": "SiLU"},
- "has_up_biases": false,
- "has_down_biases": false,
- "gate_clipping": null,
- "up_clipping": null,
- "activation_to_gate": false
- },
- "post_mlp_norm_config": null
- }
- "#;
-
- let ground_truth_config = TransformerLayerConfig {
- pre_attention_norm_config: Some(NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- }),
- pre_mlp_norm_config: NormalizationConfig {
- scale_precision: ConfigDataType::BFloat16,
- accumulation_precision: ConfigDataType::Float32,
- epsilon: 1e-5,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- use_bias: false,
- },
- mixer_config: MixerConfig::Attention(AttentionConfig {
- qkv_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- out_projection_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- query_norm_config: None,
- key_norm_config: None,
- num_heads: Some(12),
- num_groups: Some(12),
- head_dim: Some(64),
- is_causal: Some(false),
- scale: None,
- sliding_window_size: None,
- logit_soft_cap: None,
- has_sinks: false,
- has_qkv_biases: false,
- has_out_biases: false,
- has_gate: false,
- gate_projection_config: None,
- use_rope: true,
- partial_rope_dim: None,
- }),
- mlp_config: MLPConfig::Dense(mlp::DenseMLPConfig {
- linear_config: LinearConfig::QLoRA {
- quantization: QuantizationConfig {
- group_size: 32,
- weight_quantization_mode: QuantizationMode::UINT4,
- activation_quantization_mode: Some(QuantizationMode::INT8),
- activation_precision: ConfigDataType::BFloat16,
- },
- lora_rank: 16,
- lora_scale: 2.0,
- },
- activation: ActivationConfig::silu_default(),
- has_up_biases: false,
- has_down_biases: false,
- gate_clipping: None,
- up_clipping: None,
- activation_to_gate: false,
- }),
- post_attention_norm_config: None,
- post_mlp_norm_config: None,
- };
-
- let deserialized_config: TransformerLayerConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
-}
diff --git a/crates/benchmarks/src/runner/runner.rs b/crates/benchmarks/src/runner/runner.rs
index 272d6c64e..7f4eea8cc 100644
--- a/crates/benchmarks/src/runner/runner.rs
+++ b/crates/benchmarks/src/runner/runner.rs
@@ -68,11 +68,8 @@ impl Runner {
let mut session = ChatSession::new(PathBuf::from(self.model_path.clone()), decoding_config)?;
- let precision = session
- .model_metadata
- .model_config
- .as_language_model()
- .map(|config| config.model_config.transformer_config.output_norm_config.scale_precision);
+ let precision =
+ session.model_metadata.model_config.model_config.transformer_config.output_norm_config.scale_precision;
let device = self.get_device_info();
diff --git a/crates/benchmarks/src/runner/types/result.rs b/crates/benchmarks/src/runner/types/result.rs
index 7f90530f2..417702c7c 100644
--- a/crates/benchmarks/src/runner/types/result.rs
+++ b/crates/benchmarks/src/runner/types/result.rs
@@ -9,7 +9,7 @@ pub struct Result {
pub device: Device,
pub engine_version: String,
pub timestamp: u64,
- pub precision: Option<ConfigDataType>,
+ pub precision: ConfigDataType,
pub memory_used: Option<u64>,
pub tokens_count_input: u64,
pub tokens_count_output: u64,