A high-performance inference engine for AI models
Better testing (#254)
uuuvn6b1f81b8eeed
diff --git a/.config/nextest.toml b/.config/nextest.tomlnew file mode 100644index 000000000..2cad2fa40--- /dev/null+++ b/.config/nextest.toml@@ -0,0 +1,9 @@+[profile.default]+slow-timeout = { period = "20s" } # TODO: there should be no slow tests `, terminate-after = 1`++[[profile.default.overrides]]+filter = 'test(/::heavy::/)'+threads-required = "num-test-threads"++[profile.ci]+fail-fast = falsediff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.ymlindex ae3577a08..8e98fee84 100644--- a/.github/actions/setup/action.yml+++ b/.github/actions/setup/action.yml@@ -14,11 +14,17 @@ inputs:description: "Download test model"required: falsedefault: 'false'+ nextest:+ description: "Install nextest"+ required: false+ default: 'false'runs:using: compositesteps:- uses: dtolnay/rust-toolchain@stable+ - if: inputs.nextest == 'true'+ uses: taiki-e/install-action@nextest- if: inputs.linters == 'true'run: |arch -arm64 brew install clang-formatdiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 75caafcf6..571d035fc 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -70,6 +70,7 @@ jobs:with:metal: truetest_model: true+ nextest: true- name: Build cratesrun: |@@ -77,4 +78,4 @@ jobs:- name: Run testsrun: |- cargo test ${{ matrix.tracing && '--features tracing' || '' }}+ cargo nextest run --profile=ci ${{ matrix.tracing && '--features tracing' || '' }}diff --git a/.gitignore b/.gitignoreindex 93142ca42..178d23cf6 100644--- a/.gitignore+++ b/.gitignore@@ -1,6 +1,7 @@*.pdb**/mutants.out*/*.DS_Store+*.proptest-regressions.idea/# Metal tracesdiff --git a/Cargo.lock b/Cargo.lockindex 9937dc855..5b411e5c5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -346,6 +346,21 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]name = "bitflags"version = "2.10.0"@@ -2911,6 +2926,31 @@ dependencies = ["yansi",]+[[package]]+name = "proptest"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37566cb3fdacef14c0737f9546df7cfeadbfbc9fef10991038bf5015d0c80532"+dependencies = [+ "bit-set",+ "bit-vec",+ "bitflags",+ "num-traits",+ "rand 0.9.2",+ "rand_chacha 0.9.0",+ "rand_xorshift",+ "regex-syntax 0.8.9",+ "rusty-fork",+ "tempfile",+ "unarray",+]++[[package]]+name = "quick-error"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"+[[package]]name = "quote"version = "1.0.44"@@ -3002,6 +3042,25 @@ version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"+[[package]]+name = "rand_distr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8"+dependencies = [+ "num-traits",+ "rand 0.10.0",+]++[[package]]+name = "rand_xorshift"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"+dependencies = [+ "rand_core 0.9.5",+]+[[package]]name = "rawpointer"version = "0.2.1"@@ -3356,6 +3415,18 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "rusty-fork"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"+dependencies = [+ "fnv",+ "quick-error",+ "tempfile",+ "wait-timeout",+]+[[package]]name = "ryu"version = "1.0.23"@@ -3812,6 +3883,17 @@ dependencies = ["winapi-util",]+[[package]]+name = "test-tag"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5a2455608f6a56fc2ce66c89dd005501c169688f29165468e65f0b47e060333"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "thiserror"version = "1.0.69"@@ -4221,6 +4303,12 @@ version = "0.1.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"+[[package]]+name = "unarray"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"+[[package]]name = "uncased"version = "0.9.10"@@ -4375,8 +4463,10 @@ dependencies = ["objc2-foundation","prettyplease","proc-macro2",+ "proptest","quote","rand 0.10.0",+ "rand_distr","regex","schemars","serde",@@ -4385,6 +4475,7 @@ dependencies = ["syn 2.0.114","sysinfo","tempfile",+ "test-tag","thiserror 2.0.18","tokenizers","tokio",@@ -4412,6 +4503,15 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "wait-timeout"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"+dependencies = [+ "libc",+]+[[package]]name = "walkdir"version = "2.5.0"diff --git a/Cargo.toml b/Cargo.tomlindex ae3d2dab6..9ff6e7c77 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -38,6 +38,7 @@ minijinja = "2.15"minijinja-contrib = { version = "2.15", features = ["pycompat"] }clap = { version = "4.5", features = ["derive"] }rand = "0.10"+rand_distr = "0.6.0"sysinfo = "0.38"itertools = "0.14"schemars = { version = "1.2", features = ["derive"] }@@ -70,6 +71,8 @@ autocxx = "0.30"cxx = "1.0"cmake = "0.1"autocxx-build = "0.30"+test-tag = "0.1.6"+proptest = "1.10.0"# optimize the build script in debug builds[profile.dev.build-override]@@ -77,3 +80,7 @@ opt-level = 3[profile.release]lto = "thin"++# optimize tests+[profile.test]+opt-level = 2diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.tomlindex de8de29ef..33d592042 100644--- a/crates/uzu/Cargo.toml+++ b/crates/uzu/Cargo.toml@@ -42,6 +42,9 @@ objc2.workspace = trueobjc2-foundation.workspace = true[dev-dependencies]+test-tag.workspace = true+proptest.workspace = true+rand_distr.workspace = trueis_close.workspace = trueserde_json5.workspace = trueschemars.workspace = truediff --git a/crates/uzu/tests/attention_kernel_test.rs b/crates/uzu/tests/attention_kernel_test.rsindex f62a0399b..ad2d1907c 100644--- a/crates/uzu/tests/attention_kernel_test.rs+++ b/crates/uzu/tests/attention_kernel_test.rs@@ -8,6 +8,7 @@ use bytemuck;use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};use ndarray::{Array3, Array4, s};use objc2::{rc::Retained, runtime::ProtocolObject};+use test_tag::tag;use uzu::{DataType,backends::{@@ -1085,6 +1086,7 @@ fn test_two_pass_attention_gqa() {}}+#[tag(heavy)]#[test]fn perf_two_pass_attention() {use std::time::Instant;diff --git a/crates/uzu/tests/common/mod.rs b/crates/uzu/tests/common/mod.rsindex 849220505..688235123 100644--- a/crates/uzu/tests/common/mod.rs+++ b/crates/uzu/tests/common/mod.rs@@ -5,6 +5,7 @@ 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";diff --git a/crates/uzu/tests/common/proptest.rs b/crates/uzu/tests/common/proptest.rsnew file mode 100644index 000000000..4236e303c--- /dev/null+++ b/crates/uzu/tests/common/proptest.rs@@ -0,0 +1,87 @@+use std::rc::Rc;++use proptest::prelude::*;+#[cfg(feature = "metal")]+use uzu::backends::metal::Metal;+use uzu::{+ DataType,+ backends::{+ common::{Backend, Context},+ cpu::Cpu,+ },+};++pub fn kernel_data_type() -> impl Strategy<Value = DataType> {+ prop_oneof![Just(DataType::F16), Just(DataType::BF16), Just(DataType::F32)]+}++pub struct TestContextes {+ pub cpu: Rc<<Cpu as Backend>::Context>,+ #[cfg(feature = "metal")]+ pub metal: Rc<<Metal as Backend>::Context>,+}++impl TestContextes {+ pub fn new() -> TestContextes {+ TestContextes {+ cpu: <Cpu as Backend>::Context::new().expect("Failed to create Cpu context"),+ #[cfg(feature = "metal")]+ metal: <Metal as Backend>::Context::new().expect("Failed to create Metal context"),+ }+ }+}++pub struct TestResults<T> {+ pub cpu: T,+ #[cfg(feature = "metal")]+ pub metal: T,+}++#[macro_export]+macro_rules! for_each_context {+ ($CONTEXTES:ident, |$CONTEXT_NAME:ident: $CONTEXT_TYPE:ident| $body:expr) => {+ crate::common::proptest::TestResults {+ cpu: ({+ type $CONTEXT_TYPE = <uzu::backends::cpu::Cpu as uzu::backends::common::Backend>::Context;+ let $CONTEXT_NAME = $CONTEXTES.cpu.as_ref();+ $body+ })?,+ #[cfg(feature = "metal")]+ metal: ({+ type $CONTEXT_TYPE = <uzu::backends::metal::Metal as uzu::backends::common::Backend>::Context;+ let $CONTEXT_NAME = $CONTEXTES.metal.as_ref();+ $body+ })?,+ }+ };+}++pub trait ComparableTestResults {+ fn compare(+ backend: &str,+ actual: &Self,+ reference: &Self,+ ) -> Result<(), TestCaseError>;+}++impl<T: ComparableTestResults> TestResults<T> {+ pub fn compare_results(&self) -> Result<(), TestCaseError> {+ #[cfg(feature = "metal")]+ T::compare("metal", &self.metal, &self.cpu)?;++ Ok(())+ }+}++#[macro_export]+macro_rules! dispatch_dtype {+ (|()| $body:expr) => { $body };+ (|($T:ident : $dt:expr $(, $rest_T:ident : $rest_dt:expr)*)| $body:expr) => {+ match $dt {+ uzu::DataType::F16 => { type $T = half::f16; dispatch_dtype!(|($($rest_T : $rest_dt),*)| $body) }+ uzu::DataType::BF16 => { type $T = half::bf16; dispatch_dtype!(|($($rest_T : $rest_dt),*)| $body) }+ uzu::DataType::F32 => { type $T = f32; dispatch_dtype!(|($($rest_T : $rest_dt),*)| $body) }+ other => panic!("unsupported dtype in test: {:?}", other),+ }+ };+}diff --git a/crates/uzu/tests/context_mode_test.rs b/crates/uzu/tests/context_mode_test.rsindex 2c4bbaebd..a18ef59fa 100644--- a/crates/uzu/tests/context_mode_test.rs+++ b/crates/uzu/tests/context_mode_test.rs@@ -1,6 +1,7 @@mod common;use std::path::PathBuf;+use test_tag::tag;use uzu::session::{Session,config::{DecodingConfig, RunConfig, SpeculatorConfig},@@ -51,6 +52,7 @@ fn request(.to_string()}+#[tag(heavy)]#[test]fn test_context_mode_none() {let decoding_config = build_decoding_config().with_context_mode(ContextMode::None);@@ -67,6 +69,7 @@ fn test_context_mode_none() {assert_eq!(response_1, response_2);}+#[tag(heavy)]#[test]fn test_context_mode_static() {let parameter_name = "Alice".to_string();@@ -102,6 +105,7 @@ fn test_context_mode_static() {assert!(response_city.to_lowercase().contains(parameter_city.to_lowercase().as_str()));}+#[tag(heavy)]#[test]#[ignore = "Flaky test - depends on LLM output which varies even with fixed seed"]fn test_context_mode_dynamic() {@@ -144,6 +148,7 @@ fn test_context_mode_dynamic() {*/ // TODO: Fix this test}+#[tag(heavy)]#[test]fn test_context_mode_dynamic_scenario() {let decoding_config = build_decoding_config().with_context_mode(ContextMode::Dynamic);diff --git a/crates/uzu/tests/grammar_json_schema_test.rs b/crates/uzu/tests/grammar_json_schema_test.rsindex 14d6cfcf7..45cd0f53e 100644--- a/crates/uzu/tests/grammar_json_schema_test.rs+++ b/crates/uzu/tests/grammar_json_schema_test.rs@@ -6,6 +6,7 @@ mod common;use common::{RepeatSpeculator, get_test_model_path};use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use test_tag::tag;use uzu::session::{Session,config::{DecodingConfig, GrammarConfig, RunConfig, SpeculatorConfig},@@ -89,11 +90,13 @@ fn test_grammar(speculator_config: SpeculatorConfig) {}}+#[tag(heavy)]#[test]fn test_grammar_json_schema() {test_grammar(SpeculatorConfig::default());}+#[tag(heavy)]#[test]fn test_grammar_json_schema_with_speculator() {test_grammar(SpeculatorConfig {diff --git a/crates/uzu/tests/kernel/sampling/argmax_test.rs b/crates/uzu/tests/kernel/sampling/argmax_test_old.rssimilarity index 100%rename from crates/uzu/tests/kernel/sampling/argmax_test.rsrename to crates/uzu/tests/kernel/sampling/argmax_test_old.rsdiff --git a/crates/uzu/tests/kernel/sampling/mod.rs b/crates/uzu/tests/kernel/sampling/mod.rsindex 79b608c88..e87b9abd0 100644--- a/crates/uzu/tests/kernel/sampling/mod.rs+++ b/crates/uzu/tests/kernel/sampling/mod.rs@@ -1,5 +1,6 @@-mod argmax_test;+mod argmax_test_old;mod gumbel_test;mod temperature_test;+mod test_argmax;mod top_k_test;mod top_p_test;diff --git a/crates/uzu/tests/kernel/sampling/test_argmax.rs b/crates/uzu/tests/kernel/sampling/test_argmax.rsnew file mode 100644index 000000000..dfbbcb86d--- /dev/null+++ b/crates/uzu/tests/kernel/sampling/test_argmax.rs@@ -0,0 +1,131 @@+use std::mem::MaybeUninit;++use num_traits::{Float, NumCast};+use proptest::prelude::*;+use rand::{RngExt, SeedableRng, rngs::SmallRng};+use rand_distr::Normal;+use uzu::{+ ArrayElement,+ backends::common::{+ Backend, Buffer, CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,+ Context, Kernels,+ gpu_types::ArgmaxPair,+ kernel::{ArgmaxFinalKernel, ArgmaxMainKernel, ArgmaxSingleKernel},+ },+};++use crate::{+ common::proptest::{ComparableTestResults, TestContextes, kernel_data_type},+ dispatch_dtype, for_each_context,+};++struct ArgmaxTestResults(Box<[u32]>);++impl ComparableTestResults for ArgmaxTestResults {+ fn compare(+ backend: &str,+ actual: &ArgmaxTestResults,+ reference: &ArgmaxTestResults,+ ) -> Result<(), TestCaseError> {+ prop_assert_eq!(&actual.0, &reference.0, "{} doesn't match cpu", backend);++ Ok(())+ }+}++fn do_argmax_backend<B: Backend, T: ArrayElement + Float>(+ context: &B::Context,+ logits: &[T],+ batch_size: usize,+ vocab_size: usize,+) -> Result<ArgmaxTestResults, TestCaseError> {+ let logits_buffer = context.create_buffer(logits.len() * std::mem::size_of::<T>()).unwrap();+ unsafe {+ std::slice::from_raw_parts_mut::<T>(logits_buffer.cpu_ptr().as_ptr() as *mut T, logits.len())+ .copy_from_slice(logits);+ }++ let mut twopass_partial_results_buffer =+ context.create_buffer(batch_size * vocab_size.div_ceil(4096) * std::mem::size_of::<ArgmaxPair>()).unwrap();++ let mut single_output_buffer = context.create_buffer(batch_size * 4).unwrap();+ let mut twopass_output_buffer = context.create_buffer(batch_size * 4).unwrap();++ let single_kernel = <B::Kernels as Kernels>::ArgmaxSingleKernel::new(context, T::data_type()).unwrap();+ let twopass_kernel_main = <B::Kernels as Kernels>::ArgmaxMainKernel::new(context, T::data_type()).unwrap();+ let twopass_kernel_final = <B::Kernels as Kernels>::ArgmaxFinalKernel::new(context).unwrap();++ let mut command_buffer = context.create_command_buffer().unwrap().start_encoding();+ single_kernel.encode(+ &logits_buffer,+ &mut single_output_buffer,+ batch_size as u32,+ vocab_size as u32,+ &mut command_buffer,+ );+ twopass_kernel_main.encode(+ &logits_buffer,+ &mut twopass_partial_results_buffer,+ batch_size as u32,+ vocab_size as u32,+ &mut command_buffer,+ );+ twopass_kernel_final.encode(+ &twopass_partial_results_buffer,+ &mut twopass_output_buffer,+ batch_size as u32,+ vocab_size as u32,+ &mut command_buffer,+ );+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();++ let single_output = unsafe {+ std::slice::from_raw_parts(single_output_buffer.cpu_ptr().as_ptr() as *const u32, batch_size)+ .iter()+ .copied()+ .collect()+ };++ let twopass_output = unsafe {+ std::slice::from_raw_parts(twopass_output_buffer.cpu_ptr().as_ptr() as *const u32, batch_size)+ .iter()+ .copied()+ .collect()+ };++ prop_assert_eq!(&single_output, &twopass_output, "single and twopass argmax output differs");++ Ok(ArgmaxTestResults(single_output))+}++fn do_argmax<T: ArrayElement + Float>(+ contextes: &TestContextes,+ seed: u64,+ batch_size: usize,+ vocab_size: usize,+) -> Result<(), TestCaseError> {+ let mut rng = SmallRng::seed_from_u64(seed);+ let distribution = Normal::new(0.0, 32.0).unwrap();+ let mut logits: Box<[MaybeUninit<T>]> = Box::new_uninit_slice(batch_size * vocab_size);+ for logit in logits.iter_mut() {+ logit.write(<T as NumCast>::from(rng.sample(distribution)).unwrap());+ }+ let logits = unsafe { logits.assume_init() };++ for_each_context!(contextes, |context: C| do_argmax_backend::<<C as Context>::Backend, T>(+ context,+ logits.as_ref(),+ batch_size,+ vocab_size+ ))+ .compare_results()+}++#[test]+fn test_argmax_prop() {+ let contextes = TestContextes::new();++ proptest!(|(data_type in kernel_data_type(), seed in any::<u64>().no_shrink(), batch_size in (1usize..=7usize), vocab_size in (1usize..=123456usize))| {+ dispatch_dtype!(|(T: data_type)| do_argmax::<T>(&contextes, seed, batch_size, vocab_size)?);+ });+}diff --git a/crates/uzu/tests/parameters_loader_test.rs b/crates/uzu/tests/parameters_loader_test.rsindex f9ef609cb..accf5c52a 100644--- a/crates/uzu/tests/parameters_loader_test.rs+++ b/crates/uzu/tests/parameters_loader_test.rs@@ -3,6 +3,7 @@ mod common;// New integration test for ParameterLoaderuse half::bf16;use is_close::is_close;+use test_tag::tag;use uzu::{backends::{common::{Backend, Context},@@ -11,6 +12,7 @@ use uzu::{parameters::ParameterLoader,};+#[tag(heavy)]#[test]fn test_parameter_loader_basic() {let weights_path = crate::common::get_test_weights_path();diff --git a/crates/uzu/tests/text_session_test.rs b/crates/uzu/tests/text_session_test.rsindex 22be26ab6..2fe1b0e17 100644--- a/crates/uzu/tests/text_session_test.rs+++ b/crates/uzu/tests/text_session_test.rs@@ -1,6 +1,7 @@mod common;use std::path::PathBuf;+use test_tag::tag;use uzu::session::{Session,config::{DecodingConfig, RunConfig},@@ -21,11 +22,13 @@ fn build_default_text() -> String {return text;}+#[tag(heavy)]#[test]fn test_text_session_base() {run(build_default_text(), build_decoding_config(), 128);}+#[tag(heavy)]#[test]fn test_text_session_scenario() {let system_prompt = String::from("You are a helpful assistant.");@@ -33,6 +36,7 @@ fn test_text_session_scenario() {run_scenario(Some(system_prompt), user_prompts);}+#[tag(heavy)]#[test]fn test_text_session_stability() {let mut session = Session::new(build_model_path(), build_decoding_config()).unwrap();