Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

lib.rs mods visibility (#271)

Aleksandr Golokoz9803b0ba92df
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 43fb5416d..84249cefd 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -5,7 +5,7 @@ on:
branches:
- main
pull_request:
- types: [opened, reopened, ready_for_review, synchronize]
+ types: [ opened, reopened, ready_for_review, synchronize ]
workflow_dispatch:
concurrency:
@@ -23,7 +23,7 @@ defaults:
jobs:
linters:
name: linters
- runs-on: [self-hosted, macos, x64, mac, m3max, runner2]
+ runs-on: [ self-hosted, macos, x64, mac, m3max, runner2 ]
steps:
- uses: actions/checkout@v6
@@ -47,14 +47,15 @@ jobs:
git diff --exit-code -- Cargo.lock
tests:
- name: ${{ matrix.backend }} ${{ matrix.tracing && ' (tracing)' || '' }}
- runs-on: [self-hosted, macos, x64, mac, m3max, runner1]
+ name: ${{ matrix.backend }} ${{ matrix.tracing && ' (tracing)' || '' }} ${{ matrix.audio && ' (audio-runtime)' || '' }}
+ runs-on: [ self-hosted, macos, x64, mac, m3max, runner1 ]
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }}
strategy:
matrix:
- backend: ['cpu', 'metal']
- tracing: [false, true]
+ backend: [ 'cpu', 'metal' ]
+ tracing: [ false, true ]
+ audio: [ false, true ]
env:
CARGO_ENCODED_RUSTFLAGS: "-Dwarnings"
@@ -69,8 +70,15 @@ jobs:
- name: Build crates
run: |
- cargo +stable build --no-default-features ${{ matrix.backend != 'cpu' && format('--features {0}', matrix.backend) || '' }} ${{ matrix.tracing && '--features tracing' || '' }}
+ cargo +stable build --no-default-features \
+ ${{ matrix.backend != 'cpu' && format('--features {0}', matrix.backend) || '' }} \
+ ${{ matrix.tracing && '--features tracing' || '' }} \
+ ${{ matrix.audio && '--features audio-runtime' || '' }}
- name: Run tests
run: |
- cargo +stable nextest run --profile=ci --no-default-features ${{ matrix.backend != 'cpu' && format('--features {0}', matrix.backend) || '' }} ${{ matrix.tracing && '--features tracing' || '' }}
+ cargo +stable nextest run --profile=ci \
+ --no-default-features \
+ ${{ matrix.backend != 'cpu' && format('--features {0}', matrix.backend) || '' }} \
+ --features tracing \
+ --features audio-runtime
diff --git a/crates/benchmarks/src/runner/types/result.rs b/crates/benchmarks/src/runner/types/result.rs
index 5d7125552..c25082c87 100644
--- a/crates/benchmarks/src/runner/types/result.rs
+++ b/crates/benchmarks/src/runner/types/result.rs
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
-use uzu::config::ConfigDataType;
+use uzu::ConfigDataType;
use crate::runner::types::{Device, Task};
diff --git a/crates/cli/src/server/state.rs b/crates/cli/src/server/state.rs
index 345e0cc43..5e977e5ad 100644
--- a/crates/cli/src/server/state.rs
+++ b/crates/cli/src/server/state.rs
@@ -6,14 +6,13 @@ use std::{
use console::Style;
use indicatif::{ProgressBar, ProgressStyle};
use uzu::{
- prelude::{SamplingSeed, SpeculatorConfig},
+ prelude::{NGramSpeculator, SamplingSeed, SpeculatorConfig},
session::{
Session,
config::{DecodingConfig, RunConfig},
parameter::PrefillStepSize,
types::{Error, Input, Output},
},
- speculators::ngram_speculator::NGramSpeculator,
};
pub trait RunSession {
@@ -98,7 +97,6 @@ pub fn load_session(
parts.get(2).map(|s| s.parse().expect("invalid temperature, expected float"));
let speculator = Arc::new(NGramSpeculator::load_with_temperature(speculator_path, temperature));
-
SpeculatorConfig::new(number_of_speculated_tokens, speculator)
},
None => SpeculatorConfig::default(),
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index ad78a8c06..a2da1559f 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -81,13 +81,13 @@ tracing = []
audio-runtime = []
[[test]]
-name = "kernel"
-path = "tests/kernel/mod.rs"
+name = "integration"
+path = "tests/integration/mod.rs"
[[test]]
-name = "moe"
-path = "tests/moe/mod.rs"
+name = "kernel"
+path = "tests/unit/kernel/mod.rs"
[[test]]
-name = "matmul_perf_test"
-path = "tests/matmul_perf_test/main.rs"
+name = "performance"
+path = "tests/performance/mod.rs"
diff --git a/crates/uzu/src/audio/types.rs b/crates/uzu/src/audio/types.rs
index 60364a049..be933455d 100644
--- a/crates/uzu/src/audio/types.rs
+++ b/crates/uzu/src/audio/types.rs
@@ -282,49 +282,5 @@ impl AudioTokenGrid {
}
#[cfg(test)]
-mod tests {
- use super::{AudioError, AudioTokenGrid, AudioTokenPacking};
-
- #[test]
- fn packing_conversion_roundtrip_is_lossless() {
- let grid = AudioTokenGrid::new(
- vec![
- 0, 1, 2, 3, // b0 f0, f1
- 4, 5, 6, 7, // b1 f0, f1
- ]
- .into_boxed_slice(),
- 2,
- 2,
- 2,
- vec![2, 2].into_boxed_slice(),
- AudioTokenPacking::FrameMajor,
- )
- .expect("valid grid");
-
- let converted = grid.to_packing(AudioTokenPacking::CodebookMajor);
- let restored = converted.to_packing(AudioTokenPacking::FrameMajor);
-
- assert_eq!(restored, grid);
- }
-
- #[test]
- fn invalid_grid_shape_is_rejected() {
- let error = AudioTokenGrid::new(
- vec![0, 1, 2].into_boxed_slice(),
- 1,
- 2,
- 2,
- vec![2].into_boxed_slice(),
- AudioTokenPacking::FrameMajor,
- )
- .expect_err("shape mismatch should fail");
-
- assert!(matches!(
- error,
- AudioError::InvalidTokenShape {
- expected_tokens: 4,
- actual_tokens: 3
- }
- ));
- }
-}
+#[path = "../../tests/unit/audio/types_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/backends/common/kernel/kv_cache_update.rs b/crates/uzu/src/backends/common/kernel/kv_cache_update.rs
index def3ce934..d208d7156 100644
--- a/crates/uzu/src/backends/common/kernel/kv_cache_update.rs
+++ b/crates/uzu/src/backends/common/kernel/kv_cache_update.rs
@@ -119,20 +119,5 @@ pub fn create_swaps_direct(
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_direct_swaps() {
- let sources = [0, 2, 4];
- let destinations = [1, 3, 5];
- let swaps = create_swaps_direct(&sources, &destinations);
- assert_eq!(swaps.len(), 3);
- assert_eq!(swaps[0].source, 0);
- assert_eq!(swaps[0].destination, 1);
- assert_eq!(swaps[1].source, 2);
- assert_eq!(swaps[1].destination, 3);
- assert_eq!(swaps[2].source, 4);
- assert_eq!(swaps[2].destination, 5);
- }
-}
+#[path = "../../../../tests/unit/backends/common/kernel/kv_cache_update_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/backends/common/kernel/quant_matmul.rs b/crates/uzu/src/backends/common/kernel/quant_matmul.rs
index e63b12039..ee92a9b76 100644
--- a/crates/uzu/src/backends/common/kernel/quant_matmul.rs
+++ b/crates/uzu/src/backends/common/kernel/quant_matmul.rs
@@ -510,3 +510,7 @@ fn kernel_key_name(key: KernelKey) -> &'static str {
KernelKey::MatrixMatrix(MatrixMatrixFamily::QmmTransposed64x64) => "matrix_matrix_qmm_transposed_64x64",
}
}
+
+#[cfg(test)]
+#[path = "../../../../tests/unit/backends/common/kernel/quant_matmul_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/backends/common/kernel/ssd_prefill.rs b/crates/uzu/src/backends/common/kernel/ssd_prefill.rs
index cbd8a3f28..cb57d9f33 100644
--- a/crates/uzu/src/backends/common/kernel/ssd_prefill.rs
+++ b/crates/uzu/src/backends/common/kernel/ssd_prefill.rs
@@ -132,3 +132,7 @@ impl<B: Backend> SSDPrefillKernels<B> {
}
}
}
+
+#[cfg(test)]
+#[path = "../../../../tests/unit/backends/common/kernel/ssd_prefill_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/backends/cpu/argmax.rs b/crates/uzu/src/backends/cpu/argmax.rs
index 9e6212780..afa61d24b 100644
--- a/crates/uzu/src/backends/cpu/argmax.rs
+++ b/crates/uzu/src/backends/cpu/argmax.rs
@@ -181,115 +181,5 @@ pub fn neon_optimized_argmax<T: ArrayElement>(input: &[T]) -> usize {
}
#[cfg(test)]
-mod tests {
- use std::time::Instant;
-
- use super::*;
-
- #[cfg(target_arch = "aarch64")]
- #[test]
- fn test_neon_argmax_correctness() {
- // Single deterministic 64k array test with random values
- const SIZE: usize = 64 * 1024;
- const SEED: u64 = 12345;
-
- // Simple deterministic random number generator
- let mut rng_state = SEED;
- let mut data = Vec::with_capacity(SIZE);
-
- for _ in 0..SIZE {
- rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
- let random_f32 = (rng_state as f32) / (u64::MAX as f32);
- data.push(random_f32);
- }
-
- // Set a known max at position 42_000
- data[42_000] = f32::MAX;
-
- // Compute expected result with naive method
- let expected = simple_argmax(&data);
- // Compare NEON result to expected
- let neon_result = neon_optimized_argmax(&data);
-
- assert_eq!(expected, neon_result, "64k array test failed: expected {}, got {}", expected, neon_result);
- assert_eq!(expected, 42_000, "Expected max should be at index 42_000");
- }
-
- #[cfg(target_arch = "aarch64")]
- #[test]
- fn test_neon_performance_128k() {
- const SEQ_LEN: usize = 128 * 1024;
- let batch_size = 2;
- const SEED: u64 = 67890;
-
- // Generate random data with deterministic seed
- let mut rng_state = SEED;
- let mut data = Vec::with_capacity(batch_size * SEQ_LEN);
-
- for _ in 0..(batch_size * SEQ_LEN) {
- rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
- let random_f32 = (rng_state as f32) / (u64::MAX as f32);
- data.push(random_f32);
- }
-
- // Set known max positions
- let expected_indices = vec![42_000, 100_000];
- for (batch_idx, &max_pos) in expected_indices.iter().enumerate() {
- let offset = batch_idx * SEQ_LEN + max_pos;
- data[offset] = f32::MAX;
- }
-
- // Test each batch separately
- for (batch_idx, &expected_idx) in expected_indices.iter().enumerate() {
- let start_offset = batch_idx * SEQ_LEN;
- let end_offset = start_offset + SEQ_LEN;
- let batch_data = &data[start_offset..end_offset];
-
- // Test with NEON implementation
- let start = Instant::now();
- let neon_result = neon_optimized_argmax(batch_data);
- let neon_duration = start.elapsed();
-
- // Test with simple implementation
- let start = Instant::now();
- let simple_result = simple_argmax(batch_data);
- let simple_duration = start.elapsed();
-
- // Test with optimized implementation (manual unrolling)
- let start = Instant::now();
- let optimized_result = optimized_argmax(batch_data);
- let optimized_duration = start.elapsed();
-
- if batch_idx == 0 {
- println!("128k argmax performance comparison:");
- println!("NEON: {:.3} ms", neon_duration.as_secs_f64() * 1000.0);
- println!("Simple: {:.3} ms", simple_duration.as_secs_f64() * 1000.0);
- println!("Optimized: {:.3} ms", optimized_duration.as_secs_f64() * 1000.0);
-
- if simple_duration.as_nanos() > 0 && neon_duration.as_nanos() > 0 {
- let speedup_simple = simple_duration.as_secs_f64() / neon_duration.as_secs_f64();
- let speedup_optimized = optimized_duration.as_secs_f64() / neon_duration.as_secs_f64();
- println!("NEON vs Simple speedup: {:.2}x", speedup_simple);
- println!("NEON vs Optimized speedup: {:.2}x", speedup_optimized);
- }
- }
-
- // Verify all methods give the same result
- assert_eq!(
- neon_result, expected_idx,
- "NEON: Batch {} argmax mismatch: expected {}, got {}",
- batch_idx, expected_idx, neon_result
- );
- assert_eq!(
- simple_result, expected_idx,
- "Simple: Batch {} argmax mismatch: expected {}, got {}",
- batch_idx, expected_idx, simple_result
- );
- assert_eq!(
- optimized_result, expected_idx,
- "Optimized: Batch {} argmax mismatch: expected {}, got {}",
- batch_idx, expected_idx, optimized_result
- );
- }
- }
-}
+#[path = "../../../tests/unit/backends/cpu/argmax_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/classifier/classifier_context.rs b/crates/uzu/src/classifier/classifier_context.rs
index 2b3a6e4e1..dff68ae99 100644
--- a/crates/uzu/src/classifier/classifier_context.rs
+++ b/crates/uzu/src/classifier/classifier_context.rs
@@ -2,7 +2,7 @@ use std::{cell::RefCell, fs::File, io::BufReader, path::Path, rc::Rc};
use crate::{
DataType,
- backends::common::{Backend, Context, Kernels, kernel::SigmoidKernel},
+ backends::common::{Backend, Context},
classifier::ClassifierError,
config::{ClassifierModelConfig, ModelMetadata},
encodable_block::{
@@ -30,13 +30,9 @@ pub struct ClassifierContext<B: Backend> {
pub embedding_norm: Normalization<B>,
pub layers: Box<[ClassifierLayer<B>]>,
pub output_norm: Normalization<B>,
- pub global_rope: Rc<Rope<B>>,
- pub local_rope: Option<Rc<Rope<B>>>,
pub pooling: Pooling<B>,
pub prediction_head: ClassifierPredictionHead<B>,
-
- pub sigmoid_kernel: <B::Kernels as Kernels>::SigmoidKernel,
}
impl<B: Backend> ClassifierContext<B> {
@@ -252,11 +248,6 @@ impl<B: Backend> ClassifierContext<B> {
Error::Classifier(ClassifierError::KernelCreationFailed(format!("prediction head readout: {:?}", e)))
})?;
- let sigmoid_kernel = <B::Kernels as Kernels>::SigmoidKernel::new(&context, data_type.into()).map_err(|e| {
- eprintln!("Failed to create sigmoid kernel: {:?}", e);
- Error::UnableToCreateContext(e.into())
- })?;
-
let pooling = Pooling::<B>::new(
context.as_ref(),
data_type,
@@ -288,11 +279,8 @@ impl<B: Backend> ClassifierContext<B> {
embedding_norm,
layers,
output_norm,
- global_rope,
- local_rope,
pooling,
prediction_head,
- sigmoid_kernel,
})
}
diff --git a/crates/uzu/src/classifier/mod.rs b/crates/uzu/src/classifier/mod.rs
index 5857dc8b4..8b7ed08d3 100644
--- a/crates/uzu/src/classifier/mod.rs
+++ b/crates/uzu/src/classifier/mod.rs
@@ -8,7 +8,5 @@ pub use classifier_context::ClassifierContext;
pub use error::ClassifierError;
pub use result::{ClassificationOutput, ClassificationStats};
-// Re-export encodables for convenience
-pub use crate::encodable_block::{ClassifierLayer, ClassifierPredictionHead, Pooling};
#[cfg(feature = "tracing")]
-pub use crate::forward_pass::traces::{ActivationTrace, LayerActivationTrace};
+pub use crate::forward_pass::traces::ActivationTrace;
diff --git a/crates/uzu/src/config/attention.rs b/crates/uzu/src/config/attention.rs
index c5b8cf042..d74cdb3fe 100644
--- a/crates/uzu/src/config/attention.rs
+++ b/crates/uzu/src/config/attention.rs
@@ -27,89 +27,5 @@ pub struct AttentionConfig {
}
#[cfg(test)]
-mod tests {
- 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
- }
- "#;
-
- 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,
- partial_rope_dim: None,
- };
-
- let deserialized_config: AttentionConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
- }
-}
+#[path = "../../tests/unit/config/attention_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/decoder.rs b/crates/uzu/src/config/decoder.rs
index 9b5538492..0abc49511 100644
--- a/crates/uzu/src/config/decoder.rs
+++ b/crates/uzu/src/config/decoder.rs
@@ -223,395 +223,5 @@ impl DecoderConfig {
}
#[cfg(test)]
-mod tests {
- 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
- },
- "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,
- },
- 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,
- },
- 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,
- 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,
- },
- 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
- },
- "post_mixer_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "activation": {
- "type": "GELU"
- }
- },
- "post_mlp_norm_config": null
- },
- {
- "pre_mixer_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mixer_config": {
- "type": "AttentionConfig",
- "qkv_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "out_projection_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "query_norm_config": null,
- "key_norm_config": null,
- "num_heads": 4,
- "num_groups": 1,
- "head_dim": 256,
- "is_causal": true,
- "scale": 0.0625,
- "sliding_window_size": 256,
- "logit_soft_cap": null,
- "has_sinks": false,
- "has_qkv_biases": false,
- "has_out_biases": false
- },
- "post_mixer_norm_config": null,
- "pre_mlp_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "mlp_config": {
- "type": "DenseMLPConfig",
- "linear_config": {
- "type": "FullPrecisionLinearConfig",
- "precision": "bfloat16"
- },
- "activation": {
- "type": "GELU"
- }
- },
- "post_mlp_norm_config": null
- }
- ],
- "output_norm_config": {
- "scale_precision": "bfloat16",
- "accumulation_precision": "float32",
- "epsilon": 1e-06,
- "scale_offset": 1.0,
- "upcast_mode": "full_layer"
- },
- "vocab_size": 32000,
- "model_dim": 1152,
- "hidden_dim": 6912,
- "context_length": 32768
- }
- "#;
-
- let config: DecoderConfig = from_str(config_str).unwrap();
- assert_eq!(config.num_layers, 2);
- assert_eq!(config.num_heads, 4);
- assert_eq!(config.num_groups, 1);
- assert_eq!(config.head_dim, 256);
- assert_eq!(config.attention_scale, Some(0.0625));
- let sliding_windows = config.sliding_window_sizes.unwrap();
- assert_eq!(sliding_windows.len(), 2);
- assert_eq!(sliding_windows[0], Some(512));
- assert_eq!(sliding_windows[1], Some(256));
- let layer_types = config.layer_types.unwrap();
- assert!(matches!(layer_types[0], DecoderLayerType::Transformer));
- assert_eq!(config.layer_configs.unwrap().len(), 2);
- }
-}
+#[path = "../../tests/unit/config/decoder_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/decoder_layer.rs b/crates/uzu/src/config/decoder_layer.rs
index a6be7f5a2..5a85c4df0 100644
--- a/crates/uzu/src/config/decoder_layer.rs
+++ b/crates/uzu/src/config/decoder_layer.rs
@@ -101,166 +101,5 @@ impl DecoderLayerConfig {
}
#[cfg(test)]
-mod tests {
- 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
- },
- "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,
- },
- 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,
- },
- 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,
- 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);
- }
-}
+#[path = "../../tests/unit/config/decoder_layer_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/embedding.rs b/crates/uzu/src/config/embedding.rs
index 5e298212d..78d79de4c 100644
--- a/crates/uzu/src/config/embedding.rs
+++ b/crates/uzu/src/config/embedding.rs
@@ -80,63 +80,5 @@ impl EmbeddingConfig {
}
#[cfg(test)]
-mod tests {
- 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);
- }
-}
+#[path = "../../tests/unit/config/embedding_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/linear.rs b/crates/uzu/src/config/linear.rs
index ce68e481c..287367936 100644
--- a/crates/uzu/src/config/linear.rs
+++ b/crates/uzu/src/config/linear.rs
@@ -47,37 +47,5 @@ impl LinearConfig {
}
#[cfg(test)]
-mod tests {
- 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);
- }
-}
+#[path = "../../tests/unit/config/linear_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/mlp.rs b/crates/uzu/src/config/mlp.rs
index 49e088c91..96587e03e 100644
--- a/crates/uzu/src/config/mlp.rs
+++ b/crates/uzu/src/config/mlp.rs
@@ -59,173 +59,5 @@ pub struct MoeExpertConfig {
}
#[cfg(test)]
-mod tests {
- 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);
- }
-}
+#[path = "../../tests/unit/config/mlp_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/normalization/normalization_config.rs b/crates/uzu/src/config/normalization/normalization_config.rs
index 5d07d492c..95ffb212d 100644
--- a/crates/uzu/src/config/normalization/normalization_config.rs
+++ b/crates/uzu/src/config/normalization/normalization_config.rs
@@ -15,33 +15,5 @@ pub struct NormalizationConfig {
}
#[cfg(test)]
-mod tests {
- 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,
- };
-
- let deserialized_config: NormalizationConfig = from_str(config_str).unwrap();
- assert_eq!(deserialized_config, ground_truth_config);
- }
-}
+#[path = "../../../tests/unit/config/normalization/normalization_config_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/rope.rs b/crates/uzu/src/config/rope.rs
index 1f1290c13..8e9754fb3 100644
--- a/crates/uzu/src/config/rope.rs
+++ b/crates/uzu/src/config/rope.rs
@@ -61,39 +61,5 @@ impl RoPEConfig {
}
#[cfg(test)]
-mod tests {
- 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);
- }
-}
+#[path = "../../tests/unit/config/rope_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/config/transformer_layer.rs b/crates/uzu/src/config/transformer_layer.rs
index dd76cf2e6..686ba8f11 100644
--- a/crates/uzu/src/config/transformer_layer.rs
+++ b/crates/uzu/src/config/transformer_layer.rs
@@ -21,174 +21,5 @@ impl TransformerLayerConfig {
}
#[cfg(test)]
-mod tests {
- 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
- },
- "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,
- }),
- 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,
- },
- 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,
- 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);
- }
-}
+#[path = "../../tests/unit/config/transformer_layer_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/encodable_block/attention.rs b/crates/uzu/src/encodable_block/attention.rs
index e2ab1f4dc..aabd892f6 100644
--- a/crates/uzu/src/encodable_block/attention.rs
+++ b/crates/uzu/src/encodable_block/attention.rs
@@ -451,3 +451,7 @@ struct KernelKey {
pub head_dim: u32,
pub has_mask: bool,
}
+
+#[cfg(test)]
+#[path = "../../tests/unit/encodable_block/attention_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/encodable_block/decoder.rs b/crates/uzu/src/encodable_block/decoder.rs
index 890b474a9..c60e342b2 100644
--- a/crates/uzu/src/encodable_block/decoder.rs
+++ b/crates/uzu/src/encodable_block/decoder.rs
@@ -29,8 +29,6 @@ pub struct Decoder<B: Backend> {
pub embed: Embedding<B>,
pub layers: Box<[LayerExecutables<B>]>,
pub norm: RMSNorm<B>,
- pub global_rope: Option<Rc<Rope<B>>>,
- pub local_rope: Option<Rc<Rope<B>>>,
}
impl<B: Backend> Decoder<B> {
@@ -140,8 +138,6 @@ impl<B: Backend> Decoder<B> {
embed,
layers: layers.into_boxed_slice(),
norm: norm_block,
- global_rope,
- local_rope,
}
}
diff --git a/crates/uzu/src/encodable_block/layer/executables.rs b/crates/uzu/src/encodable_block/layer/executables.rs
index 1d2671500..0de13c75a 100644
--- a/crates/uzu/src/encodable_block/layer/executables.rs
+++ b/crates/uzu/src/encodable_block/layer/executables.rs
@@ -17,6 +17,7 @@ use crate::{
/// A single decoder layer with all its components.
pub struct LayerExecutables<B: Backend> {
+ #[cfg(feature = "tracing")]
pub layer_index: usize,
pub copy_main_to_shortcut: TensorCopy<B>,
pub pre_attention_norm: RMSNorm<B>,
@@ -224,6 +225,7 @@ impl<B: Backend> LayerExecutables<B> {
};
Self {
+ #[cfg(feature = "tracing")]
layer_index,
copy_main_to_shortcut,
pre_attention_norm,
diff --git a/crates/uzu/src/encodable_block/linear/mod.rs b/crates/uzu/src/encodable_block/linear/mod.rs
index ed6f482a5..faaf316ab 100644
--- a/crates/uzu/src/encodable_block/linear/mod.rs
+++ b/crates/uzu/src/encodable_block/linear/mod.rs
@@ -9,7 +9,7 @@ use crate::{
backends::common::{Backend, CommandBuffer},
config::LinearConfig,
forward_pass::state::{ArrayId, ForwardPassState},
- parameters::{ParameterLoaderError, ParameterTree},
+ parameters::ParameterTree,
};
pub trait Linear<B: Backend> {
@@ -26,8 +26,6 @@ pub enum LinearBlockError<B: Backend> {
QuantizedLinearError(#[source] QuantizedLinearError<B>),
#[error("FullPrecisionLinear error: {0}")]
FullPrecisionLinearError(#[source] FullPrecisionLinearError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[source] ParameterLoaderError<B>),
#[error("QLoRA linear layer not supported")]
QLoRaNotSupported,
}
diff --git a/crates/uzu/src/encodable_block/mod.rs b/crates/uzu/src/encodable_block/mod.rs
index b29cb69d1..ada33e7ab 100644
--- a/crates/uzu/src/encodable_block/mod.rs
+++ b/crates/uzu/src/encodable_block/mod.rs
@@ -26,13 +26,13 @@ pub use decoder::Decoder;
pub use embedding::Embedding;
pub use layer::LayerExecutables;
pub use layer_norm::{LayerNorm, LayerNormError};
-pub use linear::{FullPrecisionLinear, FullPrecisionLinearError, Linear, QuantizedLinear, QuantizedLinearError};
+pub use linear::Linear;
pub(crate) use mamba_mixer::MambaMixer;
-pub use mlp::{DenseMlp, Mlp, MoeBlock, MoeBlockError};
-pub use normalization::{Normalization, NormalizationError};
+pub use mlp::Mlp;
+pub use normalization::Normalization;
pub use pooling::Pooling;
pub use prediction_head::ClassifierPredictionHead;
-pub use qk_norm::{QKNorm, QKNormError};
+pub use qk_norm::QKNorm;
pub use rms_norm::{RMSNorm, RMSNormError};
pub use rope::Rope;
pub use sampling::Sampling;
diff --git a/crates/uzu/src/encodable_block/sampling.rs b/crates/uzu/src/encodable_block/sampling.rs
index f63ff47a5..8b174add0 100644
--- a/crates/uzu/src/encodable_block/sampling.rs
+++ b/crates/uzu/src/encodable_block/sampling.rs
@@ -6,7 +6,7 @@ use crate::{
DataType,
backends::common::{
Backend, CommandBuffer,
- kernel::sampling::{ArgmaxStrategy, SamplingError, SamplingKernel},
+ kernel::sampling::{SamplingError, SamplingKernel},
},
forward_pass::state::{ArrayId, ForwardPassState},
};
@@ -28,20 +28,6 @@ impl<B: Backend> Sampling<B> {
})
}
- pub fn new_with_strategy(
- context: &B::Context,
- data_type: DataType,
- max_batch_size: usize,
- max_vocab_size: usize,
- argmax_strategy: ArgmaxStrategy,
- ) -> Result<Self, SamplingError<B>> {
- let kernel =
- SamplingKernel::new_with_strategy(context, data_type, max_batch_size, max_vocab_size, argmax_strategy)?;
- Ok(Self {
- kernel,
- })
- }
-
pub fn encode(
&self,
state: &mut ForwardPassState<B>,
@@ -98,3 +84,7 @@ impl<B: Backend> Sampling<B> {
Ok(())
}
}
+
+#[cfg(test)]
+#[path = "../../tests/unit/encodable_block/sampling_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/forward_pass/kv_cache_layer.rs b/crates/uzu/src/forward_pass/kv_cache_layer.rs
index 254bc84d8..b60364064 100644
--- a/crates/uzu/src/forward_pass/kv_cache_layer.rs
+++ b/crates/uzu/src/forward_pass/kv_cache_layer.rs
@@ -464,3 +464,7 @@ impl<B: Backend> KVCacheLayer<B> {
}
}
}
+
+#[cfg(test)]
+#[path = "../../tests/unit/forward_pass/kv_cache_state_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/forward_pass/scratch_buffers.rs b/crates/uzu/src/forward_pass/scratch_buffers.rs
index a616571aa..a29fd934a 100644
--- a/crates/uzu/src/forward_pass/scratch_buffers.rs
+++ b/crates/uzu/src/forward_pass/scratch_buffers.rs
@@ -32,7 +32,6 @@ pub struct ScratchBuffers<B: Backend> {
pub ssm_inproj: Option<ArrayCell<B>>,
pub ssm_packed: Option<ArrayCell<B>>,
pub ssm_conv_padded: Option<ArrayCell<B>>,
- pub short_conv_padded: Option<ArrayCell<B>>,
pub ssm_x: Option<ArrayCell<B>>,
pub ssm_b: Option<ArrayCell<B>>,
pub ssm_c: Option<ArrayCell<B>>,
@@ -137,9 +136,6 @@ impl<B: Backend> ScratchBuffers<B> {
ssm_conv_padded: model_shape
.ssm_conv_padded_shape(max_suffix_len)
.map(|shape| alloc(&shape, act_ty, "ssm_conv_padded")),
- short_conv_padded: model_shape
- .short_conv_padded_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty, "short_conv_padded")),
ssm_x: model_shape.ssm_x_shape(max_suffix_len).map(|shape| alloc(&shape, act_ty, "ssm_x")),
ssm_b: model_shape.ssm_bc_shape(max_suffix_len).map(|shape| alloc(&shape, act_ty, "ssm_b")),
ssm_c: model_shape.ssm_bc_shape(max_suffix_len).map(|shape| alloc(&shape, act_ty, "ssm_c")),
diff --git a/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
index fa0c0beee..b5326fe4c 100644
--- a/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
@@ -10,7 +10,6 @@ pub struct LanguageModelGeneratorAuxBuffers<B: Backend> {
pub ssm_inproj: Option<ArrayCell<B>>,
pub ssm_packed: Option<ArrayCell<B>>,
pub ssm_conv_padded: Option<ArrayCell<B>>,
- pub short_conv_padded: Option<ArrayCell<B>>,
pub ssm_x: Option<ArrayCell<B>>,
pub ssm_b: Option<ArrayCell<B>>,
pub ssm_c: Option<ArrayCell<B>>,
@@ -70,11 +69,6 @@ impl<B: Backend> LanguageModelGeneratorAuxBuffers<B> {
.as_ref()
.zip(model_shape.ssm_conv_padded_shape(suffix_length))
.map(|(buf, shape)| buf.view(&shape)),
- short_conv_padded: scratch
- .short_conv_padded
- .as_ref()
- .zip(model_shape.short_conv_padded_shape(suffix_length))
- .map(|(buf, shape)| buf.view(&shape)),
ssm_x: scratch
.ssm_x
.as_ref()
diff --git a/crates/uzu/src/forward_pass/state/mod.rs b/crates/uzu/src/forward_pass/state/mod.rs
index cd34d8af3..d61b747a6 100644
--- a/crates/uzu/src/forward_pass/state/mod.rs
+++ b/crates/uzu/src/forward_pass/state/mod.rs
@@ -16,4 +16,4 @@ pub use language_model_generator_aux_buffers::LanguageModelGeneratorAuxBuffers;
pub use rope_buffers::RopeBuffers;
pub use rope_type::RopeType;
pub use shared_buffers::SharedBuffers;
-pub use state::{ClassifierModeState, ForwardPassMode, ForwardPassState, LanguageModelGeneratorModeState};
+pub use state::ForwardPassState;
diff --git a/crates/uzu/src/forward_pass/state/state.rs b/crates/uzu/src/forward_pass/state/state.rs
index c04a18ad9..58ac194b3 100644
--- a/crates/uzu/src/forward_pass/state/state.rs
+++ b/crates/uzu/src/forward_pass/state/state.rs
@@ -1,16 +1,15 @@
-use std::{
- cell::RefCell,
- collections::HashMap,
- ops::{Deref, DerefMut},
- rc::Rc,
-};
+#[cfg(feature = "tracing")]
+use std::ops::{Deref, DerefMut};
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+#[cfg(feature = "tracing")]
+use crate::backends::common::{CommandBuffer, CommandBufferEncoding};
#[cfg(feature = "tracing")]
use crate::forward_pass::traces::ActivationTrace;
use crate::{
DataType, DecoderConfig,
array::{Array, ArrayCell, ArrayCellExt},
- backends::common::{Backend, CommandBuffer, CommandBufferEncoding, Context},
+ backends::common::{Backend, Context},
forward_pass::{
cache_layers::CacheLayers,
model_shape::ModelShape,
@@ -455,14 +454,6 @@ impl<B: Backend> ForwardPassState<B> {
self.common_aux.suffix_length
}
- pub fn is_llm(&self) -> bool {
- matches!(self.mode, ForwardPassMode::LanguageModelGenerator(_))
- }
-
- pub fn is_classifier(&self) -> bool {
- matches!(self.mode, ForwardPassMode::Classifier(_))
- }
-
pub fn token_bitmask(&self) -> Option<&ArrayCell<B>> {
self.token_bitmask.as_ref()
}
@@ -474,13 +465,6 @@ impl<B: Backend> ForwardPassState<B> {
}
}
- pub fn llm_state_mut(&mut self) -> &mut LanguageModelGeneratorModeState<B> {
- match &mut self.mode {
- ForwardPassMode::LanguageModelGenerator(state) => state,
- _ => panic!("Not in LLM mode"),
- }
- }
-
pub fn classifier_state(&self) -> &ClassifierModeState<B> {
match &self.mode {
ForwardPassMode::Classifier(state) => state,
@@ -675,10 +659,6 @@ impl<B: Backend> ForwardPassState<B> {
self.llm_aux.as_ref().and_then(|aux| aux.ssm_conv_padded.clone())
}
- pub fn short_conv_padded_buffer(&self) -> Option<ArrayCell<B>> {
- self.llm_aux.as_ref().and_then(|aux| aux.short_conv_padded.clone())
- }
-
// ========================================================================
// Public API Methods (formerly trait methods)
// ========================================================================
@@ -767,14 +747,7 @@ impl<B: Backend> ForwardPassState<B> {
}
}
- pub fn copy_array(
- &self,
- source_array_id: ArrayId,
- destination_array: RefCell<Array<B>>,
- ) {
- destination_array.borrow_mut().copy_from_array(&self.arrays(&[source_array_id])[0].borrow());
- }
-
+ #[cfg(feature = "tracing")]
pub fn encode_copy_array(
&self,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
diff --git a/crates/uzu/src/language_model/grammar.rs b/crates/uzu/src/language_model/grammar.rs
index e53bd42ce..a110e5f0d 100644
--- a/crates/uzu/src/language_model/grammar.rs
+++ b/crates/uzu/src/language_model/grammar.rs
@@ -58,16 +58,6 @@ impl CompiledGrammarEngagementState {
},
}
}
-
- pub fn reset(&mut self) {
- match self {
- Self::Always => (),
- Self::Triggered {
- trigger_token_id: _,
- trigger_distance,
- } => *trigger_distance = None,
- }
- }
}
pub struct CompiledGrammar {
@@ -188,11 +178,6 @@ impl CompiledGrammar {
}
}
- pub fn reset(&mut self) {
- self.matcher.reset();
- self.engagement_state.reset();
- }
-
pub fn is_terminated(&self) -> bool {
self.matcher.is_terminated()
}
diff --git a/crates/uzu/src/language_model/language_model_generator_context.rs b/crates/uzu/src/language_model/language_model_generator_context.rs
index 296491dd2..b210b660d 100644
--- a/crates/uzu/src/language_model/language_model_generator_context.rs
+++ b/crates/uzu/src/language_model/language_model_generator_context.rs
@@ -109,15 +109,6 @@ impl<B: Backend> AsyncBuffers<B> {
pub fn reset_counter(&self) {
self.counter.set(0);
}
-
- /// Read sampled token from results buffer at given pass index
- pub fn read_result(
- &self,
- pass_idx: usize,
- ) -> u32 {
- let ptr = self.results.borrow().cpu_ptr().as_ptr() as *const u32;
- unsafe { *ptr.add(pass_idx % self.batch_size) }
- }
}
pub struct LanguageModelGeneratorContext<B: Backend> {
diff --git a/crates/uzu/src/language_model/mod.rs b/crates/uzu/src/language_model/mod.rs
index 246f4722c..14a07af90 100644
--- a/crates/uzu/src/language_model/mod.rs
+++ b/crates/uzu/src/language_model/mod.rs
@@ -5,7 +5,9 @@ pub mod language_model_generator;
pub mod language_model_generator_context;
pub mod result;
pub mod rng;
-pub mod sampler;
+
+#[cfg(feature = "tracing")]
+pub(crate) mod sampler;
// Re-export main types
pub use language_model_generator::{LanguageModelGenerator, LanguageModelGeneratorTrait};
diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rs
index 1a0c2b99d..aa04e648e 100644
--- a/crates/uzu/src/lib.rs
+++ b/crates/uzu/src/lib.rs
@@ -1,21 +1,27 @@
-pub mod array;
-pub mod audio;
+mod array;
+mod audio;
+mod classifier;
+mod config;
+mod data_type;
+mod encodable_block;
+mod forward_pass;
+mod language_model;
+mod parameters;
+mod speculators;
+#[cfg(feature = "tracing")]
+mod tracer;
+mod trie;
+mod utils;
+
pub mod backends;
-pub mod classifier;
-pub mod config;
-pub mod data_type;
-pub mod encodable_block;
-pub mod forward_pass;
-pub mod language_model;
-pub mod parameters;
pub mod prelude;
pub mod session;
-pub mod speculators;
-#[cfg(feature = "tracing")]
-pub mod tracer;
-pub mod trie;
-pub mod utils;
+pub use array::{Array, ArrayContextExt};
pub use config::*;
pub use data_type::*;
+pub use language_model::gumbel::{gumbel_float, revidx};
+pub use parameters::{ParameterLoader, read_safetensors_metadata};
+#[cfg(feature = "tracing")]
+pub use tracer::TraceValidator;
pub use utils::*;
diff --git a/crates/uzu/src/parameters/mod.rs b/crates/uzu/src/parameters/mod.rs
index c5ebfd4ac..67e9f3eaa 100644
--- a/crates/uzu/src/parameters/mod.rs
+++ b/crates/uzu/src/parameters/mod.rs
@@ -1,7 +1,7 @@
mod loader;
-pub use loader::{ParameterLeaf, ParameterLoader, ParameterLoaderError, ParameterTree, resolve_subtree};
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 safetensors_metadata::read_metadata as read_safetensors_metadata;
+pub use loader::{ParameterLeaf, ParameterLoader, ParameterLoaderError, ParameterTree, resolve_subtree};
+pub use safetensors_metadata::{HeaderLoadingError, read_metadata as read_safetensors_metadata};
diff --git a/crates/uzu/src/prelude.rs b/crates/uzu/src/prelude.rs
index bf17cd263..a12e95071 100644
--- a/crates/uzu/src/prelude.rs
+++ b/crates/uzu/src/prelude.rs
@@ -11,7 +11,9 @@
// Speculators
pub use crate::{
VERSION,
- audio::{AudioCodecRuntime, AudioPcmBatch, AudioTokenGrid, AudioTokenPacking},
+ audio::{AudioCodecRuntime, AudioError, AudioPcmBatch, AudioResult, AudioTokenGrid, AudioTokenPacking},
+ backends::metal::MetalContext,
+ parameters::{HeaderLoadingError, ParameterLeaf, ParameterLoaderError, ParameterTree},
session::{
ChatSession, ClassificationSession,
config::{DecodingConfig, RunConfig, SpeculatorConfig},
@@ -20,5 +22,5 @@ pub use crate::{
Error, FinishReason, Input, Message, Output, ParsedText, Role, RunStats, Stats, StepStats, Text, TotalStats,
},
},
- speculators::{empty_speculator::EmptySpeculator, speculator::Speculator},
+ speculators::{empty_speculator::EmptySpeculator, ngram_speculator::NGramSpeculator, speculator::Speculator},
};
diff --git a/crates/uzu/src/tracer/mod.rs b/crates/uzu/src/tracer/mod.rs
index 7f377abaa..7a85593be 100644
--- a/crates/uzu/src/tracer/mod.rs
+++ b/crates/uzu/src/tracer/mod.rs
@@ -6,6 +6,4 @@
mod trace_validator;
-pub use trace_validator::{
- ArrayTransform, TraceValidator, TracerValidationMetrics, TracerValidationResult, TracerValidationResults,
-};
+pub use trace_validator::TraceValidator;
diff --git a/crates/uzu/src/trie.rs b/crates/uzu/src/trie.rs
index 375b876e8..e3db006b9 100644
--- a/crates/uzu/src/trie.rs
+++ b/crates/uzu/src/trie.rs
@@ -76,6 +76,7 @@ impl TrieNode {
self.next.iter_mut().find(|n| n.token == token)
}
+ #[cfg(all(feature = "tracing", test))]
pub fn token(&self) -> u64 {
self.token
}
@@ -262,3 +263,7 @@ impl<'a> FlatTrie<'a> {
(accepted_tokens, accepted_token_indices)
}
}
+
+#[cfg(test)]
+#[path = "../tests/unit/trie_test.rs"]
+mod tests;
diff --git a/crates/uzu/src/utils/model_size.rs b/crates/uzu/src/utils/model_size.rs
index 98fab6bd3..b95719b4b 100644
--- a/crates/uzu/src/utils/model_size.rs
+++ b/crates/uzu/src/utils/model_size.rs
@@ -26,34 +26,5 @@ impl ModelSize {
}
#[cfg(test)]
-mod tests {
- use std::path::PathBuf;
-
- use super::*;
- use crate::VERSION;
- pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
-
- pub fn get_test_model_path() -> PathBuf {
- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("..")
- .join("..")
- .join("models")
- .join(VERSION)
- .join(MODEL_DIR_NAME);
- if !path.exists() {
- panic!("Test model not found at {:?}. Run `./scripts/download_test_model.sh` to fetch it.", path);
- }
- path
- }
-
- #[test]
- fn test_model_size_from_path() {
- let model_path = get_test_model_path();
-
- if model_path.exists() {
- let size = ModelSize::from_path(&model_path);
- println!("Model size: {:?}", size);
- assert_eq!(size, ModelSize::Small);
- }
- }
-}
+#[path = "../../tests/unit/utils/model_size_test.rs"]
+mod tests;
diff --git a/crates/uzu/tests/common/mod.rs b/crates/uzu/tests/common/mod.rs
index 90b95e1b7..433ed3592 100644
--- a/crates/uzu/tests/common/mod.rs
+++ b/crates/uzu/tests/common/mod.rs
@@ -1,86 +1,8 @@
#![allow(dead_code)]
-use std::{collections::HashMap, path::PathBuf};
-
-use uzu::{VERSION, speculators::speculator::Speculator};
-
pub mod assert;
pub mod proptest;
-pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
-pub const MODEL_FILE_NAME: &str = "model.safetensors";
-pub const TRACES_FILE_NAME: &str = "traces.safetensors";
-
-pub fn get_test_model_path() -> PathBuf {
- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("..")
- .join("..")
- .join("models")
- .join(VERSION)
- .join(MODEL_DIR_NAME);
- if !path.exists() {
- panic!("Test model not found at {:?}. Run `./scripts/download_test_model.sh` to fetch it.", path);
- }
- path
-}
-
-pub fn get_test_weights_path() -> PathBuf {
- get_test_model_path().join(MODEL_FILE_NAME)
-}
-
-pub fn get_traces_path() -> PathBuf {
- get_test_model_path().join(TRACES_FILE_NAME)
-}
-
-pub struct StaticSpeculator {
- responses: HashMap<Vec<u64>, HashMap<u64, f32>>,
- default_response: Option<HashMap<u64, f32>>,
-}
-
-impl StaticSpeculator {
- pub fn new(responses: HashMap<Vec<u64>, HashMap<u64, f32>>) -> Self {
- Self {
- responses,
- default_response: None,
- }
- }
-
- pub fn with_default_response(default_response: HashMap<u64, f32>) -> Self {
- Self {
- responses: HashMap::new(),
- default_response: Some(default_response),
- }
- }
-}
-
-impl Speculator for StaticSpeculator {
- fn speculate(
- &self,
- prefix: &[u64],
- ) -> HashMap<u64, f32> {
- self.responses.get(prefix).cloned().or_else(|| self.default_response.clone()).unwrap_or_default()
- }
-}
-
-pub struct RepeatSpeculator;
-
-impl Speculator for RepeatSpeculator {
- fn speculate(
- &self,
- prefix: &[u64],
- ) -> HashMap<u64, f32> {
- let mut hm = HashMap::new();
-
- for (pos, token) in prefix.iter().copied().enumerate() {
- *hm.entry(token).or_insert(0.0) += f32::sqrt((1 + pos) as f32);
- }
-
- let sum = hm.values().sum::<f32>();
-
- hm.into_iter().map(|(pos, weight)| (pos, weight / sum)).collect()
- }
-}
-
/// Invokes `$body` once per available backend, with `$B` bound to each backend type.
#[macro_export]
macro_rules! for_each_backend {
diff --git a/crates/uzu/tests/integration/mod.rs b/crates/uzu/tests/integration/mod.rs
new file mode 100644
index 000000000..0cd6dd61b
--- /dev/null
+++ b/crates/uzu/tests/integration/mod.rs
@@ -0,0 +1,8 @@
+#[path = "../common/mod.rs"]
+mod common;
+mod parameters;
+mod session;
+mod tracer;
+mod util;
+
+mod person_schema_metal_bitmask_test;
diff --git a/crates/uzu/tests/parameters_loader_test.rs b/crates/uzu/tests/integration/parameters/loader_test.rs
similarity index 89%
rename from crates/uzu/tests/parameters_loader_test.rs
rename to crates/uzu/tests/integration/parameters/loader_test.rs
index 94e564709..463beae4b 100644
--- a/crates/uzu/tests/parameters_loader_test.rs
+++ b/crates/uzu/tests/integration/parameters/loader_test.rs
@@ -1,22 +1,23 @@
#![cfg(metal_backend)]
-mod common;
// New integration test for ParameterLoader
use half::bf16;
use is_close::is_close;
use test_tag::tag;
use uzu::{
+ ParameterLoader,
backends::{
common::{Backend, Context},
metal::Metal,
},
- parameters::ParameterLoader,
};
+use crate::util::path::get_test_weights_path;
+
#[tag(heavy)]
#[test]
fn test_parameter_loader_basic() {
- let weights_path = crate::common::get_test_weights_path();
+ let weights_path = get_test_weights_path();
let context = <Metal as Backend>::Context::new().expect("Failed to create MetalContext");
let file = std::fs::File::open(&weights_path).expect("Weights file not found; run download script");
diff --git a/crates/uzu/tests/integration/parameters/mod.rs b/crates/uzu/tests/integration/parameters/mod.rs
new file mode 100644
index 000000000..08e062824
--- /dev/null
+++ b/crates/uzu/tests/integration/parameters/mod.rs
@@ -0,0 +1,2 @@
+mod loader_test;
+mod safetensors_metadata_test;
diff --git a/crates/uzu/tests/integration/parameters/safetensors_metadata_test.rs b/crates/uzu/tests/integration/parameters/safetensors_metadata_test.rs
new file mode 100644
index 000000000..23a4ef027
--- /dev/null
+++ b/crates/uzu/tests/integration/parameters/safetensors_metadata_test.rs
@@ -0,0 +1,13 @@
+use std::fs::File;
+
+use uzu::read_safetensors_metadata;
+
+use crate::util::path::get_test_weights_path;
+
+#[test]
+fn test_metadata_loading() {
+ let path = get_test_weights_path();
+ let file = File::open(&path).expect("weights not found");
+ let (_offset, metadata) = read_safetensors_metadata(&file).expect("read metadata");
+ assert!(metadata.tensors.len() > 0);
+}
diff --git a/crates/uzu/tests/person_schema_metal_bitmask_test.rs b/crates/uzu/tests/integration/person_schema_metal_bitmask_test.rs
similarity index 95%
rename from crates/uzu/tests/person_schema_metal_bitmask_test.rs
rename to crates/uzu/tests/integration/person_schema_metal_bitmask_test.rs
index 92ca87fbc..0c039a76a 100644
--- a/crates/uzu/tests/person_schema_metal_bitmask_test.rs
+++ b/crates/uzu/tests/integration/person_schema_metal_bitmask_test.rs
@@ -6,7 +6,7 @@ use metal::{MTLDevice, MTLDeviceExt, MTLResourceOptions};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokenizers::Tokenizer;
-use uzu::{DataType, array::Array, backends::metal::Metal};
+use uzu::{Array, DataType, backends::metal::Metal};
use xgrammar::{DLDevice, DLDeviceType, DLTensor, Grammar, GrammarCompiler, GrammarMatcher, TokenizerInfo};
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
@@ -21,7 +21,7 @@ fn person_schema_metal_bitmask() {
let crate_version = env!("CARGO_PKG_VERSION");
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let repo_root = manifest_dir.parent().unwrap().parent().unwrap();
- let model_dir = repo_root.join("models").join(crate_version).join("Llama-3.2-1B-Instruct");
+ let model_dir = repo_root.join("../../../../models").join(crate_version).join("Llama-3.2-1B-Instruct");
let tokenizer_path = model_dir.join("tokenizer.json");
if !tokenizer_path.exists() {
diff --git a/crates/uzu/tests/context_mode_test.rs b/crates/uzu/tests/integration/session/chat_session/context_mode_test.rs
similarity index 98%
rename from crates/uzu/tests/context_mode_test.rs
rename to crates/uzu/tests/integration/session/chat_session/context_mode_test.rs
index 0815def03..af31c1f20 100644
--- a/crates/uzu/tests/context_mode_test.rs
+++ b/crates/uzu/tests/integration/session/chat_session/context_mode_test.rs
@@ -1,7 +1,5 @@
#![cfg(metal_backend)]
-mod common;
-
use std::path::PathBuf;
use test_tag::tag;
@@ -14,8 +12,10 @@ use uzu::session::{
types::{Input, Message, Output},
};
+use crate::util::path::get_test_model_path;
+
fn build_model_path() -> PathBuf {
- common::get_test_model_path()
+ get_test_model_path()
}
fn build_decoding_config() -> DecodingConfig {
diff --git a/crates/uzu/tests/integration/session/chat_session/mod.rs b/crates/uzu/tests/integration/session/chat_session/mod.rs
new file mode 100644
index 000000000..1527a7fb4
--- /dev/null
+++ b/crates/uzu/tests/integration/session/chat_session/mod.rs
@@ -0,0 +1,2 @@
+mod context_mode_test;
+mod text_session_test;
diff --git a/crates/uzu/tests/text_session_test.rs b/crates/uzu/tests/integration/session/chat_session/text_session_test.rs
similarity index 88%
rename from crates/uzu/tests/text_session_test.rs
rename to crates/uzu/tests/integration/session/chat_session/text_session_test.rs
index ef46240f9..97f56b578 100644
--- a/crates/uzu/tests/text_session_test.rs
+++ b/crates/uzu/tests/integration/session/chat_session/text_session_test.rs
@@ -1,9 +1,5 @@
#![cfg(metal_backend)]
-mod common;
-
-use std::path::PathBuf;
-
use test_tag::tag;
use uzu::session::{
Session,
@@ -12,17 +8,14 @@ use uzu::session::{
types::{Input, Message, Output},
};
-fn build_model_path() -> PathBuf {
- common::get_test_model_path()
-}
+use crate::util::path::get_test_model_path;
fn build_decoding_config() -> DecodingConfig {
DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(42))
}
fn build_default_text() -> String {
- let text = String::from("Tell about London");
- return text;
+ String::from("Tell about London")
}
#[tag(heavy)]
@@ -42,7 +35,7 @@ fn test_text_session_scenario() {
#[tag(heavy)]
#[test]
fn test_text_session_stability() {
- let mut session = Session::new(build_model_path(), build_decoding_config()).unwrap();
+ let mut session = Session::new(get_test_model_path(), build_decoding_config()).unwrap();
println!("Index | TTFT, s | Prompt t/s | Generate t/s");
for index in 0..10 {
let input = Input::Text(build_default_text());
@@ -70,7 +63,7 @@ fn run(
decoding_config: DecodingConfig,
tokens_limit: u64,
) {
- let mut session = Session::new(build_model_path(), decoding_config).unwrap();
+ let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
let input = Input::Text(text);
let output = session
.run(
@@ -99,7 +92,7 @@ fn run_scenario(
system_prompt: Option<String>,
user_prompts: Vec<String>,
) {
- let mut session = Session::new(build_model_path(), build_decoding_config()).unwrap();
+ let mut session = Session::new(get_test_model_path(), build_decoding_config()).unwrap();
let mut messages: Vec<Message> = vec![];
if let Some(system_prompt) = system_prompt {
diff --git a/crates/uzu/tests/grammar_json_schema_test.rs b/crates/uzu/tests/integration/session/config/grammar_json_schema_test.rs
similarity index 97%
rename from crates/uzu/tests/grammar_json_schema_test.rs
rename to crates/uzu/tests/integration/session/config/grammar_json_schema_test.rs
index fbab1248b..f8c4095e9 100644
--- a/crates/uzu/tests/grammar_json_schema_test.rs
+++ b/crates/uzu/tests/integration/session/config/grammar_json_schema_test.rs
@@ -2,8 +2,6 @@
use std::sync::Arc;
-mod common;
-use common::{RepeatSpeculator, get_test_model_path};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use test_tag::tag;
@@ -14,6 +12,8 @@ use uzu::session::{
types::Input,
};
+use crate::util::{path::get_test_model_path, speculator::RepeatSpeculator};
+
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct Address {
street: String,
diff --git a/crates/uzu/tests/integration/session/config/mod.rs b/crates/uzu/tests/integration/session/config/mod.rs
new file mode 100644
index 000000000..c162be941
--- /dev/null
+++ b/crates/uzu/tests/integration/session/config/mod.rs
@@ -0,0 +1 @@
+mod grammar_json_schema_test;
diff --git a/crates/uzu/tests/integration/session/mod.rs b/crates/uzu/tests/integration/session/mod.rs
new file mode 100644
index 000000000..a81650b2a
--- /dev/null
+++ b/crates/uzu/tests/integration/session/mod.rs
@@ -0,0 +1,2 @@
+mod chat_session;
+mod config;
diff --git a/crates/uzu/tests/integration/tracer/mod.rs b/crates/uzu/tests/integration/tracer/mod.rs
new file mode 100644
index 000000000..a2ccc7ca3
--- /dev/null
+++ b/crates/uzu/tests/integration/tracer/mod.rs
@@ -0,0 +1 @@
+mod trace_validator_test;
diff --git a/crates/uzu/tests/tracer_test.rs b/crates/uzu/tests/integration/tracer/trace_validator_test.rs
similarity index 86%
rename from crates/uzu/tests/tracer_test.rs
rename to crates/uzu/tests/integration/tracer/trace_validator_test.rs
index ec6999ce4..a98bf2cdc 100644
--- a/crates/uzu/tests/tracer_test.rs
+++ b/crates/uzu/tests/integration/tracer/trace_validator_test.rs
@@ -1,19 +1,14 @@
#![cfg(all(metal_backend, feature = "tracing"))]
-mod common;
-use std::path::PathBuf;
+use uzu::{TraceValidator, backends::metal::Metal};
-use uzu::{backends::metal::Metal, tracer::TraceValidator};
-
-fn build_model_path() -> PathBuf {
- common::get_test_model_path()
-}
+use crate::util::path::{get_test_model_path, get_traces_path};
#[test]
fn test_tracer() {
- let model_path = build_model_path();
+ let model_path = get_test_model_path();
// Ensure traces file present, otherwise skip
- let traces_path = crate::common::get_traces_path();
+ let traces_path = get_traces_path();
if !traces_path.exists() {
println!("Skipping tracer test: traces file missing at {:?}", traces_path);
return;
diff --git a/crates/uzu/tests/integration/util/mod.rs b/crates/uzu/tests/integration/util/mod.rs
new file mode 100644
index 000000000..6b0e55f15
--- /dev/null
+++ b/crates/uzu/tests/integration/util/mod.rs
@@ -0,0 +1,2 @@
+pub mod path;
+pub mod speculator;
diff --git a/crates/uzu/tests/integration/util/path.rs b/crates/uzu/tests/integration/util/path.rs
new file mode 100644
index 000000000..0c3867ae7
--- /dev/null
+++ b/crates/uzu/tests/integration/util/path.rs
@@ -0,0 +1,30 @@
+use std::path::PathBuf;
+
+pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
+pub const MODEL_FILE_NAME: &str = "model.safetensors";
+pub const TRACES_FILE_NAME: &str = "traces.safetensors";
+
+pub fn get_version() -> &'static str {
+ env!("CARGO_PKG_VERSION")
+}
+
+pub fn get_test_model_path() -> PathBuf {
+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .join("models")
+ .join(get_version())
+ .join(MODEL_DIR_NAME);
+ if !path.exists() {
+ panic!("Test model not found at {:?}. Run `./scripts/download_test_model.sh` to fetch it.", path);
+ }
+ path
+}
+
+pub fn get_test_weights_path() -> PathBuf {
+ get_test_model_path().join(MODEL_FILE_NAME)
+}
+
+pub fn get_traces_path() -> PathBuf {
+ get_test_model_path().join(TRACES_FILE_NAME)
+}
diff --git a/crates/uzu/tests/integration/util/speculator.rs b/crates/uzu/tests/integration/util/speculator.rs
new file mode 100644
index 000000000..d3359a710
--- /dev/null
+++ b/crates/uzu/tests/integration/util/speculator.rs
@@ -0,0 +1,22 @@
+use std::collections::HashMap;
+
+use uzu::prelude::Speculator;
+
+pub struct RepeatSpeculator;
+
+impl Speculator for RepeatSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ let mut hm = HashMap::new();
+
+ for (pos, token) in prefix.iter().copied().enumerate() {
+ *hm.entry(token).or_insert(0.0) += f32::sqrt((1 + pos) as f32);
+ }
+
+ let sum = hm.values().sum::<f32>();
+
+ hm.into_iter().map(|(pos, weight)| (pos, weight / sum)).collect()
+ }
+}
diff --git a/crates/uzu/tests/matmul_perf_test/bench.rs b/crates/uzu/tests/performance/matmul/bench.rs
similarity index 100%
rename from crates/uzu/tests/matmul_perf_test/bench.rs
rename to crates/uzu/tests/performance/matmul/bench.rs
diff --git a/crates/uzu/tests/matmul_perf_test/error.rs b/crates/uzu/tests/performance/matmul/error.rs
similarity index 100%
rename from crates/uzu/tests/matmul_perf_test/error.rs
rename to crates/uzu/tests/performance/matmul/error.rs
diff --git a/crates/uzu/tests/matmul_perf_test/main.rs b/crates/uzu/tests/performance/matmul/main.rs
similarity index 95%
rename from crates/uzu/tests/matmul_perf_test/main.rs
rename to crates/uzu/tests/performance/matmul/main.rs
index fd7eee941..ff03e5348 100644
--- a/crates/uzu/tests/matmul_perf_test/main.rs
+++ b/crates/uzu/tests/performance/matmul/main.rs
@@ -1,14 +1,7 @@
#![cfg(all(target_os = "macos", metal_backend))]
-mod bench;
-mod error;
-mod output;
-mod shapes;
-
use indicatif::{ProgressBar, ProgressStyle};
use metal::MTLDeviceExt;
-use output::print_results_table;
-use shapes::test_shapes;
use uzu::{
DataType,
backends::{
@@ -17,6 +10,8 @@ use uzu::{
},
};
+use crate::matmul::{bench, output::print_results_table, shapes::test_shapes};
+
type Ctx = <Metal as Backend>::Context;
fn write_json_results<T: serde::Serialize>(
diff --git a/crates/uzu/tests/performance/matmul/mod.rs b/crates/uzu/tests/performance/matmul/mod.rs
new file mode 100644
index 000000000..f79669fac
--- /dev/null
+++ b/crates/uzu/tests/performance/matmul/mod.rs
@@ -0,0 +1,6 @@
+mod main;
+
+mod bench;
+mod error;
+mod output;
+mod shapes;
diff --git a/crates/uzu/tests/matmul_perf_test/output.rs b/crates/uzu/tests/performance/matmul/output.rs
similarity index 100%
rename from crates/uzu/tests/matmul_perf_test/output.rs
rename to crates/uzu/tests/performance/matmul/output.rs
diff --git a/crates/uzu/tests/matmul_perf_test/shapes.rs b/crates/uzu/tests/performance/matmul/shapes.rs
similarity index 100%
rename from crates/uzu/tests/matmul_perf_test/shapes.rs
rename to crates/uzu/tests/performance/matmul/shapes.rs
diff --git a/crates/uzu/tests/performance/mod.rs b/crates/uzu/tests/performance/mod.rs
new file mode 100644
index 000000000..2ecbda881
--- /dev/null
+++ b/crates/uzu/tests/performance/mod.rs
@@ -0,0 +1 @@
+mod matmul;
diff --git a/crates/uzu/tests/safetensors_metadata_test.rs b/crates/uzu/tests/safetensors_metadata_test.rs
deleted file mode 100644
index 289c85261..000000000
--- a/crates/uzu/tests/safetensors_metadata_test.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod common;
-
-use std::fs::File;
-
-use uzu::parameters::read_safetensors_metadata as read_metadata;
-
-#[test]
-fn test_metadata_loading() {
- let path = crate::common::get_test_weights_path();
- let file = File::open(&path).expect("weights not found");
- let (_offset, metadata) = read_metadata(&file).expect("read metadata");
- assert!(metadata.tensors.len() > 0);
-}
diff --git a/crates/uzu/tests/unit/audio/types_test.rs b/crates/uzu/tests/unit/audio/types_test.rs
new file mode 100644
index 000000000..bc66cb593
--- /dev/null
+++ b/crates/uzu/tests/unit/audio/types_test.rs
@@ -0,0 +1,44 @@
+use super::{AudioError, AudioTokenGrid, AudioTokenPacking};
+
+#[test]
+fn packing_conversion_roundtrip_is_lossless() {
+ let grid = AudioTokenGrid::new(
+ vec![
+ 0, 1, 2, 3, // b0 f0, f1
+ 4, 5, 6, 7, // b1 f0, f1
+ ]
+ .into_boxed_slice(),
+ 2,
+ 2,
+ 2,
+ vec![2, 2].into_boxed_slice(),
+ AudioTokenPacking::FrameMajor,
+ )
+ .expect("valid grid");
+
+ let converted = grid.to_packing(AudioTokenPacking::CodebookMajor);
+ let restored = converted.to_packing(AudioTokenPacking::FrameMajor);
+
+ assert_eq!(restored, grid);
+}
+
+#[test]
+fn invalid_grid_shape_is_rejected() {
+ let error = AudioTokenGrid::new(
+ vec![0, 1, 2].into_boxed_slice(),
+ 1,
+ 2,
+ 2,
+ vec![2].into_boxed_slice(),
+ AudioTokenPacking::FrameMajor,
+ )
+ .expect_err("shape mismatch should fail");
+
+ assert!(matches!(
+ error,
+ AudioError::InvalidTokenShape {
+ expected_tokens: 4,
+ actual_tokens: 3
+ }
+ ));
+}
diff --git a/crates/uzu/tests/kv_cache_update_test.rs b/crates/uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs
similarity index 87%
rename from crates/uzu/tests/kv_cache_update_test.rs
rename to crates/uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs
index 8f704c09d..9afec7e7d 100644
--- a/crates/uzu/tests/kv_cache_update_test.rs
+++ b/crates/uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs
@@ -5,12 +5,10 @@ use std::{cell::RefCell, rc::Rc};
use bytemuck;
use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};
use ndarray::{Array, Array3, s};
-use uzu::backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
- gpu_types::Swap,
- kernel::kv_cache_update::{KVCacheUpdate, KVLayerData, create_swaps_direct},
- },
+
+use super::*;
+use crate::backends::{
+ common::{CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context},
metal::Metal,
};
@@ -49,7 +47,7 @@ fn test_random_pattern(context: &<Metal as Backend>::Context) {
println!("Testing with random pattern...");
let max_sequence_length = 256usize;
- let kv_cache_update = match KVCacheUpdate::new(context, uzu::DataType::F32, max_sequence_length) {
+ let kv_cache_update = match KVCacheUpdate::new(context, DataType::F32, max_sequence_length) {
Ok(update) => update,
Err(e) => {
println!("Warning: Failed to create KV cache update: {:?}. Skipping test.", e);
@@ -142,3 +140,17 @@ fn test_random_pattern(context: &<Metal as Backend>::Context) {
assert_eq!(key_result, expected_keys);
assert_eq!(value_result, expected_values);
}
+
+#[test]
+fn test_direct_swaps() {
+ let sources = [0, 2, 4];
+ let destinations = [1, 3, 5];
+ let swaps = create_swaps_direct(&sources, &destinations);
+ assert_eq!(swaps.len(), 3);
+ assert_eq!(swaps[0].source, 0);
+ assert_eq!(swaps[0].destination, 1);
+ assert_eq!(swaps[1].source, 2);
+ assert_eq!(swaps[1].destination, 3);
+ assert_eq!(swaps[2].source, 4);
+ assert_eq!(swaps[2].destination, 5);
+}
diff --git a/crates/uzu/tests/quant_matmul_test.rs b/crates/uzu/tests/unit/backends/common/kernel/quant_matmul_test.rs
similarity index 99%
rename from crates/uzu/tests/quant_matmul_test.rs
rename to crates/uzu/tests/unit/backends/common/kernel/quant_matmul_test.rs
index b3065829a..e60458411 100644
--- a/crates/uzu/tests/quant_matmul_test.rs
+++ b/crates/uzu/tests/unit/backends/common/kernel/quant_matmul_test.rs
@@ -6,7 +6,8 @@ use bytemuck;
use half::{bf16, f16};
use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};
use objc2::{rc::Retained, runtime::ProtocolObject};
-use uzu::{
+
+use crate::{
DataType,
backends::{
common::{
diff --git a/crates/uzu/tests/ssd_prefill_kernel_test.rs b/crates/uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs
similarity index 99%
rename from crates/uzu/tests/ssd_prefill_kernel_test.rs
rename to crates/uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs
index 4bde961ec..83cf9fa95 100644
--- a/crates/uzu/tests/ssd_prefill_kernel_test.rs
+++ b/crates/uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs
@@ -5,7 +5,8 @@ use std::mem::size_of;
use bytemuck;
use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};
use objc2::runtime::ProtocolObject;
-use uzu::{
+
+use crate::{
DataType,
backends::{
common::{
diff --git a/crates/uzu/tests/unit/backends/cpu/argmax_test.rs b/crates/uzu/tests/unit/backends/cpu/argmax_test.rs
new file mode 100644
index 000000000..36e45590e
--- /dev/null
+++ b/crates/uzu/tests/unit/backends/cpu/argmax_test.rs
@@ -0,0 +1,110 @@
+use std::time::Instant;
+
+use super::*;
+
+#[cfg(target_arch = "aarch64")]
+#[test]
+fn test_neon_argmax_correctness() {
+ // Single deterministic 64k array test with random values
+ const SIZE: usize = 64 * 1024;
+ const SEED: u64 = 12345;
+
+ // Simple deterministic random number generator
+ let mut rng_state = SEED;
+ let mut data = Vec::with_capacity(SIZE);
+
+ for _ in 0..SIZE {
+ rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
+ let random_f32 = (rng_state as f32) / (u64::MAX as f32);
+ data.push(random_f32);
+ }
+
+ // Set a known max at position 42_000
+ data[42_000] = f32::MAX;
+
+ // Compute expected result with naive method
+ let expected = simple_argmax(&data);
+ // Compare NEON result to expected
+ let neon_result = neon_optimized_argmax(&data);
+
+ assert_eq!(expected, neon_result, "64k array test failed: expected {}, got {}", expected, neon_result);
+ assert_eq!(expected, 42_000, "Expected max should be at index 42_000");
+}
+
+#[cfg(target_arch = "aarch64")]
+#[test]
+fn test_neon_performance_128k() {
+ const SEQ_LEN: usize = 128 * 1024;
+ let batch_size = 2;
+ const SEED: u64 = 67890;
+
+ // Generate random data with deterministic seed
+ let mut rng_state = SEED;
+ let mut data = Vec::with_capacity(batch_size * SEQ_LEN);
+
+ for _ in 0..(batch_size * SEQ_LEN) {
+ rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
+ let random_f32 = (rng_state as f32) / (u64::MAX as f32);
+ data.push(random_f32);
+ }
+
+ // Set known max positions
+ let expected_indices = vec![42_000, 100_000];
+ for (batch_idx, &max_pos) in expected_indices.iter().enumerate() {
+ let offset = batch_idx * SEQ_LEN + max_pos;
+ data[offset] = f32::MAX;
+ }
+
+ // Test each batch separately
+ for (batch_idx, &expected_idx) in expected_indices.iter().enumerate() {
+ let start_offset = batch_idx * SEQ_LEN;
+ let end_offset = start_offset + SEQ_LEN;
+ let batch_data = &data[start_offset..end_offset];
+
+ // Test with NEON implementation
+ let start = Instant::now();
+ let neon_result = neon_optimized_argmax(batch_data);
+ let neon_duration = start.elapsed();
+
+ // Test with simple implementation
+ let start = Instant::now();
+ let simple_result = simple_argmax(batch_data);
+ let simple_duration = start.elapsed();
+
+ // Test with optimized implementation (manual unrolling)
+ let start = Instant::now();
+ let optimized_result = optimized_argmax(batch_data);
+ let optimized_duration = start.elapsed();
+
+ if batch_idx == 0 {
+ println!("128k argmax performance comparison:");
+ println!("NEON: {:.3} ms", neon_duration.as_secs_f64() * 1000.0);
+ println!("Simple: {:.3} ms", simple_duration.as_secs_f64() * 1000.0);
+ println!("Optimized: {:.3} ms", optimized_duration.as_secs_f64() * 1000.0);
+
+ if simple_duration.as_nanos() > 0 && neon_duration.as_nanos() > 0 {
+ let speedup_simple = simple_duration.as_secs_f64() / neon_duration.as_secs_f64();
+ let speedup_optimized = optimized_duration.as_secs_f64() / neon_duration.as_secs_f64();
+ println!("NEON vs Simple speedup: {:.2}x", speedup_simple);
+ println!("NEON vs Optimized speedup: {:.2}x", speedup_optimized);
+ }
+ }
+
+ // Verify all methods give the same result
+ assert_eq!(
+ neon_result, expected_idx,
+ "NEON: Batch {} argmax mismatch: expected {}, got {}",
+ batch_idx, expected_idx, neon_result
+ );
+ assert_eq!(
+ simple_result, expected_idx,
+ "Simple: Batch {} argmax mismatch: expected {}, got {}",
+ batch_idx, expected_idx, simple_result
+ );
+ assert_eq!(
+ optimized_result, expected_idx,
+ "Optimized: Batch {} argmax mismatch: expected {}, got {}",
+ batch_idx, expected_idx, optimized_result
+ );
+ }
+}
diff --git a/crates/uzu/tests/unit/config/attention_test.rs b/crates/uzu/tests/unit/config/attention_test.rs
new file mode 100644
index 000000000..6eb9b9016
--- /dev/null
+++ b/crates/uzu/tests/unit/config/attention_test.rs
@@ -0,0 +1,84 @@
+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
+ }
+ "#;
+
+ 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,
+ partial_rope_dim: None,
+ };
+
+ let deserialized_config: AttentionConfig = from_str(config_str).unwrap();
+ assert_eq!(deserialized_config, ground_truth_config);
+}
diff --git a/crates/uzu/tests/unit/config/decoder_layer_test.rs b/crates/uzu/tests/unit/config/decoder_layer_test.rs
new file mode 100644
index 000000000..f437d261c
--- /dev/null
+++ b/crates/uzu/tests/unit/config/decoder_layer_test.rs
@@ -0,0 +1,161 @@
+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
+ },
+ "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,
+ },
+ 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,
+ },
+ 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,
+ 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/uzu/tests/unit/config/decoder_test.rs b/crates/uzu/tests/unit/config/decoder_test.rs
new file mode 100644
index 000000000..4c5473b97
--- /dev/null
+++ b/crates/uzu/tests/unit/config/decoder_test.rs
@@ -0,0 +1,390 @@
+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
+ },
+ "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,
+ },
+ 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,
+ },
+ 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,
+ 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,
+ },
+ 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
+ },
+ "post_mixer_norm_config": null,
+ "pre_mlp_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mlp_config": {
+ "type": "DenseMLPConfig",
+ "linear_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "activation": {
+ "type": "GELU"
+ }
+ },
+ "post_mlp_norm_config": null
+ },
+ {
+ "pre_mixer_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mixer_config": {
+ "type": "AttentionConfig",
+ "qkv_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "out_projection_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "query_norm_config": null,
+ "key_norm_config": null,
+ "num_heads": 4,
+ "num_groups": 1,
+ "head_dim": 256,
+ "is_causal": true,
+ "scale": 0.0625,
+ "sliding_window_size": 256,
+ "logit_soft_cap": null,
+ "has_sinks": false,
+ "has_qkv_biases": false,
+ "has_out_biases": false
+ },
+ "post_mixer_norm_config": null,
+ "pre_mlp_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "mlp_config": {
+ "type": "DenseMLPConfig",
+ "linear_config": {
+ "type": "FullPrecisionLinearConfig",
+ "precision": "bfloat16"
+ },
+ "activation": {
+ "type": "GELU"
+ }
+ },
+ "post_mlp_norm_config": null
+ }
+ ],
+ "output_norm_config": {
+ "scale_precision": "bfloat16",
+ "accumulation_precision": "float32",
+ "epsilon": 1e-06,
+ "scale_offset": 1.0,
+ "upcast_mode": "full_layer"
+ },
+ "vocab_size": 32000,
+ "model_dim": 1152,
+ "hidden_dim": 6912,
+ "context_length": 32768
+ }
+ "#;
+
+ let config: DecoderConfig = from_str(config_str).unwrap();
+ assert_eq!(config.num_layers, 2);
+ assert_eq!(config.num_heads, 4);
+ assert_eq!(config.num_groups, 1);
+ assert_eq!(config.head_dim, 256);
+ assert_eq!(config.attention_scale, Some(0.0625));
+ let sliding_windows = config.sliding_window_sizes.unwrap();
+ assert_eq!(sliding_windows.len(), 2);
+ assert_eq!(sliding_windows[0], Some(512));
+ assert_eq!(sliding_windows[1], Some(256));
+ let layer_types = config.layer_types.unwrap();
+ assert!(matches!(layer_types[0], DecoderLayerType::Transformer));
+ assert_eq!(config.layer_configs.unwrap().len(), 2);
+}
diff --git a/crates/uzu/tests/unit/config/embedding_test.rs b/crates/uzu/tests/unit/config/embedding_test.rs
new file mode 100644
index 000000000..85f1af7b0
--- /dev/null
+++ b/crates/uzu/tests/unit/config/embedding_test.rs
@@ -0,0 +1,58 @@
+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/uzu/tests/unit/config/linear_test.rs b/crates/uzu/tests/unit/config/linear_test.rs
new file mode 100644
index 000000000..844af1a4e
--- /dev/null
+++ b/crates/uzu/tests/unit/config/linear_test.rs
@@ -0,0 +1,32 @@
+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);
+}
diff --git a/crates/uzu/tests/unit/config/mlp_test.rs b/crates/uzu/tests/unit/config/mlp_test.rs
new file mode 100644
index 000000000..b9254a480
--- /dev/null
+++ b/crates/uzu/tests/unit/config/mlp_test.rs
@@ -0,0 +1,168 @@
+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/uzu/tests/unit/config/normalization/normalization_config_test.rs b/crates/uzu/tests/unit/config/normalization/normalization_config_test.rs
new file mode 100644
index 000000000..b420a6ed1
--- /dev/null
+++ b/crates/uzu/tests/unit/config/normalization/normalization_config_test.rs
@@ -0,0 +1,28 @@
+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,
+ };
+
+ let deserialized_config: NormalizationConfig = from_str(config_str).unwrap();
+ assert_eq!(deserialized_config, ground_truth_config);
+}
diff --git a/crates/uzu/tests/unit/config/rope_test.rs b/crates/uzu/tests/unit/config/rope_test.rs
new file mode 100644
index 000000000..9213b5bfc
--- /dev/null
+++ b/crates/uzu/tests/unit/config/rope_test.rs
@@ -0,0 +1,34 @@
+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/uzu/tests/unit/config/transformer_layer_test.rs b/crates/uzu/tests/unit/config/transformer_layer_test.rs
new file mode 100644
index 000000000..5889e1f5d
--- /dev/null
+++ b/crates/uzu/tests/unit/config/transformer_layer_test.rs
@@ -0,0 +1,169 @@
+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
+ },
+ "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,
+ }),
+ 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,
+ },
+ 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,
+ 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/uzu/tests/attention_kernel_test.rs b/crates/uzu/tests/unit/encodable_block/attention_test.rs
similarity index 99%
rename from crates/uzu/tests/attention_kernel_test.rs
rename to crates/uzu/tests/unit/encodable_block/attention_test.rs
index bc311814b..86c4c5c66 100644
--- a/crates/uzu/tests/attention_kernel_test.rs
+++ b/crates/uzu/tests/unit/encodable_block/attention_test.rs
@@ -1,7 +1,5 @@
#![cfg(metal_backend)]
-mod common;
-
use std::mem::size_of;
use bytemuck;
@@ -9,7 +7,8 @@ use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};
use ndarray::{Array3, Array4, s};
use objc2::{rc::Retained, runtime::ProtocolObject};
use test_tag::tag;
-use uzu::{
+
+use crate::{
DataType,
backends::{
common::{
diff --git a/crates/uzu/tests/sampling_test.rs b/crates/uzu/tests/unit/encodable_block/sampling_test.rs
similarity index 99%
rename from crates/uzu/tests/sampling_test.rs
rename to crates/uzu/tests/unit/encodable_block/sampling_test.rs
index 85ba5a08a..70ad296bf 100644
--- a/crates/uzu/tests/sampling_test.rs
+++ b/crates/uzu/tests/unit/encodable_block/sampling_test.rs
@@ -1,12 +1,11 @@
#![cfg(metal_backend)]
-mod common;
-
use bytemuck;
use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};
use rand::seq::SliceRandom;
+
// for Vec::shuffle
-use uzu::{
+use crate::{
DataType,
backends::{
common::{
diff --git a/crates/uzu/tests/kv_cache_state_test.rs b/crates/uzu/tests/unit/forward_pass/kv_cache_state_test.rs
similarity index 99%
rename from crates/uzu/tests/kv_cache_state_test.rs
rename to crates/uzu/tests/unit/forward_pass/kv_cache_state_test.rs
index f176b52f7..01d5baa5f 100644
--- a/crates/uzu/tests/kv_cache_state_test.rs
+++ b/crates/uzu/tests/unit/forward_pass/kv_cache_state_test.rs
@@ -1,6 +1,6 @@
#![cfg(metal_backend)]
-use uzu::{
+use crate::{
DataType,
array::ArrayContextExt,
backends::{
diff --git a/crates/uzu/tests/kernel/activation_mul_test.rs b/crates/uzu/tests/unit/kernel/activation_mul_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/activation_mul_test.rs
rename to crates/uzu/tests/unit/kernel/activation_mul_test.rs
index d900a1452..5f4cba53b 100644
--- a/crates/uzu/tests/kernel/activation_mul_test.rs
+++ b/crates/uzu/tests/unit/kernel/activation_mul_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/attention/attention_gemm_test.rs b/crates/uzu/tests/unit/kernel/attention/attention_gemm_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/attention/attention_gemm_test.rs
rename to crates/uzu/tests/unit/kernel/attention/attention_gemm_test.rs
index 26bc04292..7a9725809 100644
--- a/crates/uzu/tests/kernel/attention/attention_gemm_test.rs
+++ b/crates/uzu/tests/unit/kernel/attention/attention_gemm_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/attention/attention_single_pass_test.rs b/crates/uzu/tests/unit/kernel/attention/attention_single_pass_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/attention/attention_single_pass_test.rs
rename to crates/uzu/tests/unit/kernel/attention/attention_single_pass_test.rs
index 37e3a2070..b59aa67a0 100644
--- a/crates/uzu/tests/kernel/attention/attention_single_pass_test.rs
+++ b/crates/uzu/tests/unit/kernel/attention/attention_single_pass_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/attention/attention_update_kv_cache_test.rs b/crates/uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/attention/attention_update_kv_cache_test.rs
rename to crates/uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs
index 06666b65d..f06cbfda9 100644
--- a/crates/uzu/tests/kernel/attention/attention_update_kv_cache_test.rs
+++ b/crates/uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/attention/mod.rs b/crates/uzu/tests/unit/kernel/attention/mod.rs
similarity index 100%
rename from crates/uzu/tests/kernel/attention/mod.rs
rename to crates/uzu/tests/unit/kernel/attention/mod.rs
diff --git a/crates/uzu/tests/audio_codec_test.rs b/crates/uzu/tests/unit/kernel/audio/audio_test.rs
similarity index 84%
rename from crates/uzu/tests/audio_codec_test.rs
rename to crates/uzu/tests/unit/kernel/audio/audio_test.rs
index d545ef699..da86155f2 100644
--- a/crates/uzu/tests/audio_codec_test.rs
+++ b/crates/uzu/tests/unit/kernel/audio/audio_test.rs
@@ -1,12 +1,16 @@
#![cfg(all(feature = "audio-runtime", metal_backend))]
-use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue};
+use std::{
+ ops::{Deref, DerefMut},
+ rc::Rc,
+};
+
use uzu::{
- DataType,
- array::ArrayContextExt,
+ ArrayContextExt, DataType,
backends::{
common::{
- Backend, Context, Kernels,
+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
+ Context, Kernels,
kernel::{
AudioAddKernel, AudioCausalConv1dKernel, AudioCausalConvTranspose1dKernel, AudioClampKernel,
AudioConv1dKernel, AudioFsqDecodeKernel, AudioFsqEncodeKernel, AudioHalfSnakeKernel,
@@ -17,7 +21,7 @@ use uzu::{
},
};
-fn create_test_context() -> std::rc::Rc<<Metal as Backend>::Context> {
+fn create_test_context() -> Rc<<Metal as Backend>::Context> {
<Metal as Backend>::Context::new().expect("MetalContext")
}
@@ -98,15 +102,13 @@ fn audio_conv1d_replicate_matches_reference_f32() {
}
}
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- input.buffer(),
- weight.buffer(),
- bias.buffer(),
- output.buffer(),
- lengths.buffer(),
+ input.buffer().borrow().deref(),
+ weight.buffer().borrow().deref(),
+ bias.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ lengths.buffer().borrow().deref(),
cin as i32,
cout as i32,
seq_len_in as i32,
@@ -117,12 +119,9 @@ fn audio_conv1d_replicate_matches_reference_f32() {
padding as i32,
1_i32,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..output_len {
@@ -204,27 +203,22 @@ fn audio_causal_conv1d_matches_reference_f32() {
}
}
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- input.buffer(),
- weight.buffer(),
- bias.buffer(),
- output.buffer(),
- lengths_array.buffer(),
+ input.buffer().borrow().deref(),
+ weight.buffer().borrow().deref(),
+ bias.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ lengths_array.buffer().borrow().deref(),
cin as i32,
cout as i32,
seq_len as i32,
kernel_size as i32,
dilation as i32,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..output_len {
@@ -319,15 +313,13 @@ fn audio_causal_conv_transpose1d_matches_reference_f32() {
}
}
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- input.buffer(),
- weight.buffer(),
- bias.buffer(),
- output.buffer(),
- lengths.buffer(),
+ input.buffer().borrow().deref(),
+ weight.buffer().borrow().deref(),
+ bias.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ lengths.buffer().borrow().deref(),
cin as i32,
cout as i32,
seq_len_in as i32,
@@ -335,12 +327,9 @@ fn audio_causal_conv_transpose1d_matches_reference_f32() {
stride as i32,
groups as i32,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..output_len {
@@ -369,14 +358,15 @@ fn audio_leaky_relu_matches_reference_f32() {
let output = context.create_array(&[n], DataType::F32, "audio_leaky_relu_output");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
- kernel.encode(input.buffer(), output.buffer(), n as i32, slope, &mut encoder);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
+ kernel.encode(
+ input.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ n as i32,
+ slope,
+ &mut command_buffer,
+ );
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..n {
@@ -404,14 +394,14 @@ fn audio_tanh_matches_reference_f32() {
let output = context.create_array(&[n], DataType::F32, "audio_tanh_output");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
- kernel.encode(input.buffer(), output.buffer(), n as i32, &mut encoder);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
+ kernel.encode(
+ input.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ n as i32,
+ &mut command_buffer,
+ );
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..n {
@@ -443,16 +433,22 @@ fn audio_add_and_scale_match_reference_f32() {
let sum = context.create_array(&[n], DataType::F32, "audio_add_sum");
let scaled = context.create_array(&[n], DataType::F32, "audio_add_scaled");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
- add_kernel.encode(a.buffer(), b.buffer(), sum.buffer(), n as i32, &mut encoder);
-
- scale_kernel.encode(sum.buffer(), scaled.buffer(), n as i32, scale_value, &mut encoder);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
+ add_kernel.encode(
+ a.buffer().borrow().deref(),
+ b.buffer().borrow().deref(),
+ sum.buffer().borrow_mut().deref_mut(),
+ n as i32,
+ &mut command_buffer,
+ );
+ scale_kernel.encode(
+ sum.buffer().borrow().deref(),
+ scaled.buffer().borrow_mut().deref_mut(),
+ n as i32,
+ scale_value,
+ &mut command_buffer,
+ );
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let sum_got = sum.as_slice::<f32>();
let scaled_got = scaled.as_slice::<f32>();
@@ -493,14 +489,16 @@ fn audio_clamp_matches_reference_f32() {
let output = context.create_array(&[n], DataType::F32, "audio_clamp_output");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
- kernel.encode(input.buffer(), output.buffer(), n as i32, min_value, max_value, &mut encoder);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
+ kernel.encode(
+ input.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ n as i32,
+ min_value,
+ max_value,
+ &mut command_buffer,
+ );
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for index in 0..n {
@@ -536,25 +534,20 @@ fn audio_half_snake_matches_reference_f32() {
let output = context.create_array(&[batch_size, channels, seq_len], DataType::F32, "audio_half_snake_output");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- input.buffer(),
- alpha.buffer(),
- output.buffer(),
+ input.buffer().borrow().deref(),
+ alpha.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
channels as i32,
seq_len as i32,
snake_channels as i32,
negative_slope,
eps,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let got = output.as_slice::<f32>();
for batch in 0..batch_size {
@@ -607,24 +600,19 @@ fn audio_fsq_decode_matches_reference() {
let output =
context.create_array(&[batch_size, num_groups * codebook_dim, seq_len], DataType::F32, "audio_fsq_output");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- tokens.buffer(),
- output.buffer(),
- lengths.buffer(),
+ tokens.buffer().borrow().deref(),
+ output.buffer().borrow_mut().deref_mut(),
+ lengths.buffer().borrow().deref(),
num_groups as i32,
seq_len as i32,
codebook_dim as i32,
&num_levels,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let expected =
reference_fsq_decode(&[0, 7, 11, 3, 5, 9], 2, batch_size, num_groups, seq_len, codebook_dim, &num_levels);
@@ -670,13 +658,11 @@ fn audio_fsq_encode_matches_reference() {
let tokens = context.create_array(&[batch_size, num_groups, seq_len], DataType::I32, "audio_fsq_encode_tokens");
- let command_buffer = context.command_queue.command_buffer().expect("command buffer");
- let mut encoder = command_buffer.new_compute_command_encoder().expect("compute encoder");
-
+ let mut command_buffer = context.create_command_buffer().expect("command buffer").start_encoding();
kernel.encode(
- input.buffer(),
- tokens.buffer(),
- lengths.buffer(),
+ input.buffer().borrow().deref(),
+ tokens.buffer().borrow_mut().deref_mut(),
+ lengths.buffer().borrow().deref(),
num_groups as i32,
seq_len as i32,
codebook_dim as i32,
@@ -684,12 +670,9 @@ fn audio_fsq_encode_matches_reference() {
&dim_base_index,
eps,
batch_size as i32,
- &mut encoder,
+ &mut command_buffer,
);
-
- encoder.end_encoding();
- command_buffer.commit();
- command_buffer.wait_until_completed();
+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
let expected = reference_fsq_encode(
&input_values,
diff --git a/crates/uzu/tests/unit/kernel/audio/mod.rs b/crates/uzu/tests/unit/kernel/audio/mod.rs
new file mode 100644
index 000000000..0ba6abbfd
--- /dev/null
+++ b/crates/uzu/tests/unit/kernel/audio/mod.rs
@@ -0,0 +1 @@
+mod audio_test;
diff --git a/crates/uzu/tests/kernel/full_precision_embedding_test.rs b/crates/uzu/tests/unit/kernel/full_precision_embedding_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/full_precision_embedding_test.rs
rename to crates/uzu/tests/unit/kernel/full_precision_embedding_test.rs
index 2a1b61fd8..cbb24e518 100644
--- a/crates/uzu/tests/kernel/full_precision_embedding_test.rs
+++ b/crates/uzu/tests/unit/kernel/full_precision_embedding_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels, kernel::FullPrecisionEmbeddingLookupKernel,
diff --git a/crates/uzu/tests/kernel/matmul/gemv_test.rs b/crates/uzu/tests/unit/kernel/matmul/gemv_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/matmul/gemv_test.rs
rename to crates/uzu/tests/unit/kernel/matmul/gemv_test.rs
index 0b3160835..444f0b17c 100644
--- a/crates/uzu/tests/kernel/matmul/gemv_test.rs
+++ b/crates/uzu/tests/unit/kernel/matmul/gemv_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/matmul_correctness_test.rs b/crates/uzu/tests/unit/kernel/matmul/matmul_correctness_test.rs
similarity index 100%
rename from crates/uzu/tests/matmul_correctness_test.rs
rename to crates/uzu/tests/unit/kernel/matmul/matmul_correctness_test.rs
diff --git a/crates/uzu/tests/kernel/matmul/mod.rs b/crates/uzu/tests/unit/kernel/matmul/mod.rs
similarity index 100%
rename from crates/uzu/tests/kernel/matmul/mod.rs
rename to crates/uzu/tests/unit/kernel/matmul/mod.rs
diff --git a/crates/uzu/tests/kernel/matmul/steel_gemm_test.rs b/crates/uzu/tests/unit/kernel/matmul/steel_gemm_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/matmul/steel_gemm_test.rs
rename to crates/uzu/tests/unit/kernel/matmul/steel_gemm_test.rs
index 2b73062f5..103c5d53a 100644
--- a/crates/uzu/tests/kernel/matmul/steel_gemm_test.rs
+++ b/crates/uzu/tests/unit/kernel/matmul/steel_gemm_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/mod.rs b/crates/uzu/tests/unit/kernel/mod.rs
similarity index 84%
rename from crates/uzu/tests/kernel/mod.rs
rename to crates/uzu/tests/unit/kernel/mod.rs
index 0f81bd4b3..ad863e541 100644
--- a/crates/uzu/tests/kernel/mod.rs
+++ b/crates/uzu/tests/unit/kernel/mod.rs
@@ -1,15 +1,17 @@
#[macro_use]
-#[path = "../common/mod.rs"]
+#[path = "../../common/mod.rs"]
mod common;
-mod attention;
-mod matmul;
-mod sampling;
mod activation_mul_test;
+mod attention;
+mod audio;
mod full_precision_embedding_test;
+mod matmul;
+mod moe;
mod qk_norm_test;
mod rms_norm_test;
mod rope_test;
+mod sampling;
mod tensor_add_bias_test;
mod tensor_add_swap_test;
mod tensor_copy_test;
diff --git a/crates/uzu/tests/moe/counts_offsets_fused_test.rs b/crates/uzu/tests/unit/kernel/moe/counts_offsets_fused_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/counts_offsets_fused_test.rs
rename to crates/uzu/tests/unit/kernel/moe/counts_offsets_fused_test.rs
diff --git a/crates/uzu/tests/moe/mod.rs b/crates/uzu/tests/unit/kernel/moe/mod.rs
similarity index 100%
rename from crates/uzu/tests/moe/mod.rs
rename to crates/uzu/tests/unit/kernel/moe/mod.rs
diff --git a/crates/uzu/tests/moe/moe_block_e2e_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_block_e2e_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_block_e2e_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_block_e2e_test.rs
diff --git a/crates/uzu/tests/moe/moe_experts_perf_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_experts_perf_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_experts_perf_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_experts_perf_test.rs
diff --git a/crates/uzu/tests/moe/moe_experts_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_experts_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_experts_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_experts_test.rs
diff --git a/crates/uzu/tests/moe/moe_finalize_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_finalize_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_finalize_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_finalize_test.rs
diff --git a/crates/uzu/tests/moe/moe_gather_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_gather_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_gather_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_gather_test.rs
diff --git a/crates/uzu/tests/moe/moe_perf_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_perf_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_perf_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_perf_test.rs
diff --git a/crates/uzu/tests/moe/moe_router_topk_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_router_topk_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_router_topk_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_router_topk_test.rs
diff --git a/crates/uzu/tests/moe/moe_scatter_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_scatter_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_scatter_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_scatter_test.rs
diff --git a/crates/uzu/tests/moe/moe_test_utils.rs b/crates/uzu/tests/unit/kernel/moe/moe_test_utils.rs
similarity index 98%
rename from crates/uzu/tests/moe/moe_test_utils.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_test_utils.rs
index 51881427f..0cc38f135 100644
--- a/crates/uzu/tests/moe/moe_test_utils.rs
+++ b/crates/uzu/tests/unit/kernel/moe/moe_test_utils.rs
@@ -1,6 +1,6 @@
//! Shared test utilities for MoE tests
//!
-//! Contains common helper functions, CPU ground truth implementations,
+//! Contains util helper functions, CPU ground truth implementations,
//! buffer allocation helpers, and test fixtures used across all MoE test files.
#![cfg(metal_backend)]
diff --git a/crates/uzu/tests/moe/moe_tiles_test.rs b/crates/uzu/tests/unit/kernel/moe/moe_tiles_test.rs
similarity index 100%
rename from crates/uzu/tests/moe/moe_tiles_test.rs
rename to crates/uzu/tests/unit/kernel/moe/moe_tiles_test.rs
diff --git a/crates/uzu/tests/kernel/qk_norm_test.rs b/crates/uzu/tests/unit/kernel/qk_norm_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/qk_norm_test.rs
rename to crates/uzu/tests/unit/kernel/qk_norm_test.rs
index 2374b1b29..ad6d5b038 100644
--- a/crates/uzu/tests/kernel/qk_norm_test.rs
+++ b/crates/uzu/tests/unit/kernel/qk_norm_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/rms_norm_test.rs b/crates/uzu/tests/unit/kernel/rms_norm_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/rms_norm_test.rs
rename to crates/uzu/tests/unit/kernel/rms_norm_test.rs
index b74d69830..db9891942 100644
--- a/crates/uzu/tests/kernel/rms_norm_test.rs
+++ b/crates/uzu/tests/unit/kernel/rms_norm_test.rs
@@ -8,8 +8,7 @@ use half::{bf16, f16};
use num_traits::Float;
use rand::{RngExt, SeedableRng, prelude::StdRng};
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial,
@@ -122,7 +121,6 @@ fn get_output<
input: &Input<InputT, ScaleT, OutputT>
) -> (Vec<OutputT>, f64, Option<Duration>) {
let context = B::Context::new().expect("Failed to create Context");
-
let kernel = <<B as Backend>::Kernels as Kernels>::RMSNormKernel::new(
&context,
InputT::data_type(),
diff --git a/crates/uzu/tests/kernel/rope_test.rs b/crates/uzu/tests/unit/kernel/rope_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/rope_test.rs
rename to crates/uzu/tests/unit/kernel/rope_test.rs
index 1af978474..114d55fd7 100644
--- a/crates/uzu/tests/kernel/rope_test.rs
+++ b/crates/uzu/tests/unit/kernel/rope_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/sampling/argmax_test_old.rs b/crates/uzu/tests/unit/kernel/sampling/argmax_test_old.rs
similarity index 99%
rename from crates/uzu/tests/kernel/sampling/argmax_test_old.rs
rename to crates/uzu/tests/unit/kernel/sampling/argmax_test_old.rs
index 6606cff17..b64f31870 100644
--- a/crates/uzu/tests/kernel/sampling/argmax_test_old.rs
+++ b/crates/uzu/tests/unit/kernel/sampling/argmax_test_old.rs
@@ -7,8 +7,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels,
diff --git a/crates/uzu/tests/kernel/sampling/gumbel_test.rs b/crates/uzu/tests/unit/kernel/sampling/gumbel_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/sampling/gumbel_test.rs
rename to crates/uzu/tests/unit/kernel/sampling/gumbel_test.rs
index 3bb528631..4fbdce850 100644
--- a/crates/uzu/tests/kernel/sampling/gumbel_test.rs
+++ b/crates/uzu/tests/unit/kernel/sampling/gumbel_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
@@ -15,7 +14,7 @@ use uzu::{
},
cpu::Cpu,
},
- language_model::gumbel::{gumbel_float, revidx},
+ gumbel_float, revidx,
};
struct Input<T: ArrayElement + Float> {
diff --git a/crates/uzu/tests/kernel/sampling/mod.rs b/crates/uzu/tests/unit/kernel/sampling/mod.rs
similarity index 100%
rename from crates/uzu/tests/kernel/sampling/mod.rs
rename to crates/uzu/tests/unit/kernel/sampling/mod.rs
diff --git a/crates/uzu/tests/kernel/sampling/temperature_test.rs b/crates/uzu/tests/unit/kernel/sampling/temperature_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/sampling/temperature_test.rs
rename to crates/uzu/tests/unit/kernel/sampling/temperature_test.rs
index 53bbff087..77f2c4944 100644
--- a/crates/uzu/tests/kernel/sampling/temperature_test.rs
+++ b/crates/uzu/tests/unit/kernel/sampling/temperature_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/sampling/test_argmax.rs b/crates/uzu/tests/unit/kernel/sampling/test_argmax.rs
similarity index 100%
rename from crates/uzu/tests/kernel/sampling/test_argmax.rs
rename to crates/uzu/tests/unit/kernel/sampling/test_argmax.rs
diff --git a/crates/uzu/tests/kernel/sampling/top_k_test.rs b/crates/uzu/tests/unit/kernel/sampling/top_k_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/sampling/top_k_test.rs
rename to crates/uzu/tests/unit/kernel/sampling/top_k_test.rs
index 7332e26fb..39aaad087 100644
--- a/crates/uzu/tests/kernel/sampling/top_k_test.rs
+++ b/crates/uzu/tests/unit/kernel/sampling/top_k_test.rs
@@ -7,8 +7,7 @@ use half::{bf16, f16};
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::StdRng};
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
diff --git a/crates/uzu/tests/kernel/sampling/top_p_test.rs b/crates/uzu/tests/unit/kernel/sampling/top_p_test.rs
similarity index 99%
rename from crates/uzu/tests/kernel/sampling/top_p_test.rs
rename to crates/uzu/tests/unit/kernel/sampling/top_p_test.rs
index 4c773e420..8cabf92ad 100644
--- a/crates/uzu/tests/kernel/sampling/top_p_test.rs
+++ b/crates/uzu/tests/unit/kernel/sampling/top_p_test.rs
@@ -8,8 +8,7 @@ use half::{bf16, f16};
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::StdRng, seq::SliceRandom};
use uzu::{
- ArrayElement, DataType,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement, DataType,
backends::{
common::{
Backend, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial,
diff --git a/crates/uzu/tests/ssm_update_test.rs b/crates/uzu/tests/unit/kernel/ssd_update_test.rs
similarity index 100%
rename from crates/uzu/tests/ssm_update_test.rs
rename to crates/uzu/tests/unit/kernel/ssd_update_test.rs
diff --git a/crates/uzu/tests/kernel/tensor_add_bias_test.rs b/crates/uzu/tests/unit/kernel/tensor_add_bias_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/tensor_add_bias_test.rs
rename to crates/uzu/tests/unit/kernel/tensor_add_bias_test.rs
index 363849284..c77ce3f45 100644
--- a/crates/uzu/tests/kernel/tensor_add_bias_test.rs
+++ b/crates/uzu/tests/unit/kernel/tensor_add_bias_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels, kernel::TensorAddBiasKernel,
diff --git a/crates/uzu/tests/kernel/tensor_add_swap_test.rs b/crates/uzu/tests/unit/kernel/tensor_add_swap_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/tensor_add_swap_test.rs
rename to crates/uzu/tests/unit/kernel/tensor_add_swap_test.rs
index cd5926cc8..10a880822 100644
--- a/crates/uzu/tests/kernel/tensor_add_swap_test.rs
+++ b/crates/uzu/tests/unit/kernel/tensor_add_swap_test.rs
@@ -3,8 +3,7 @@ use std::{fmt::Debug, ops::DerefMut};
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels, kernel::TensorAddSwapKernel,
diff --git a/crates/uzu/tests/kernel/tensor_copy_test.rs b/crates/uzu/tests/unit/kernel/tensor_copy_test.rs
similarity index 97%
rename from crates/uzu/tests/kernel/tensor_copy_test.rs
rename to crates/uzu/tests/unit/kernel/tensor_copy_test.rs
index e56ceef41..2af7a1929 100644
--- a/crates/uzu/tests/kernel/tensor_copy_test.rs
+++ b/crates/uzu/tests/unit/kernel/tensor_copy_test.rs
@@ -6,8 +6,7 @@ use std::{
use half::{bf16, f16};
use num_traits::Float;
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels, kernel::TensorCopyKernel,
diff --git a/crates/uzu/tests/kernel/token_copy_test.rs b/crates/uzu/tests/unit/kernel/token_copy_test.rs
similarity index 98%
rename from crates/uzu/tests/kernel/token_copy_test.rs
rename to crates/uzu/tests/unit/kernel/token_copy_test.rs
index 78b2c95b9..d64315950 100644
--- a/crates/uzu/tests/kernel/token_copy_test.rs
+++ b/crates/uzu/tests/unit/kernel/token_copy_test.rs
@@ -1,8 +1,7 @@
use std::ops::{Deref, DerefMut};
use uzu::{
- ArrayElement,
- array::ArrayContextExt,
+ ArrayContextExt, ArrayElement,
backends::common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,
Kernels,
diff --git a/crates/uzu/tests/trie_test.rs b/crates/uzu/tests/unit/trie_test.rs
similarity index 92%
rename from crates/uzu/tests/trie_test.rs
rename to crates/uzu/tests/unit/trie_test.rs
index 751135df8..dd9b8c9d0 100644
--- a/crates/uzu/tests/trie_test.rs
+++ b/crates/uzu/tests/unit/trie_test.rs
@@ -1,13 +1,34 @@
use std::collections::HashMap;
-use uzu::{
+use crate::{
language_model::rng::PRng,
+ prelude::Speculator,
speculators::empty_speculator::EmptySpeculator,
trie::{TrieCreationConfig, TrieNode},
};
-mod common;
-use common::StaticSpeculator;
+pub struct StaticSpeculator {
+ responses: HashMap<Vec<u64>, HashMap<u64, f32>>,
+ default_response: Option<HashMap<u64, f32>>,
+}
+
+impl StaticSpeculator {
+ pub fn new(responses: HashMap<Vec<u64>, HashMap<u64, f32>>) -> Self {
+ Self {
+ responses,
+ default_response: None,
+ }
+ }
+}
+
+impl Speculator for StaticSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ self.responses.get(prefix).cloned().or_else(|| self.default_response.clone()).unwrap_or_default()
+ }
+}
fn verify_sprout(
trie_root: &TrieNode,
diff --git a/crates/uzu/tests/unit/utils/model_size_test.rs b/crates/uzu/tests/unit/utils/model_size_test.rs
new file mode 100644
index 000000000..077833655
--- /dev/null
+++ b/crates/uzu/tests/unit/utils/model_size_test.rs
@@ -0,0 +1,29 @@
+use std::path::PathBuf;
+
+use super::*;
+use crate::VERSION;
+pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
+
+pub fn get_test_model_path() -> PathBuf {
+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .join("models")
+ .join(VERSION)
+ .join(MODEL_DIR_NAME);
+ if !path.exists() {
+ panic!("Test model not found at {:?}. Run `./scripts/download_test_model.sh` to fetch it.", path);
+ }
+ path
+}
+
+#[test]
+fn test_model_size_from_path() {
+ let model_path = get_test_model_path();
+
+ if model_path.exists() {
+ let size = ModelSize::from_path(&model_path);
+ println!("Model size: {:?}", size);
+ assert_eq!(size, ModelSize::Small);
+ }
+}