Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Forward pass benches (#486)

Aleksandr Golokoz2600dd291698
diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.toml
index 7093bfc36..8003a73a0 100644
--- a/crates/backend-uzu/Cargo.toml
+++ b/crates/backend-uzu/Cargo.toml
@@ -116,10 +116,14 @@ path = "tests/integration/mod.rs"
name = "kernel"
path = "tests/unit/kernel/test_entry.rs"
-[[bench]]
-name = "kernel"
-path = "tests/performance/kernel/bench_entry.rs"
-
[[test]]
name = "performance"
path = "tests/performance/mod.rs"
+
+[[bench]]
+name = "benchmarks"
+path = "tests/performance/bench_entry.rs"
+
+[[bench]]
+name = "kernel"
+path = "tests/performance/kernel/bench_entry.rs"
\ No newline at end of file
diff --git a/crates/backend-uzu/src/config/model/language_model.rs b/crates/backend-uzu/src/config/model/language_model.rs
index 23b607ac7..8c398f1e9 100644
--- a/crates/backend-uzu/src/config/model/language_model.rs
+++ b/crates/backend-uzu/src/config/model/language_model.rs
@@ -1,9 +1,23 @@
+use std::{fs::File, io::BufReader, path::Path};
+
use proc_macros::uzu_config;
-use crate::config::{decoder::DecoderConfig, model::generation::GenerationConfig};
+use crate::{
+ config::{decoder::DecoderConfig, model::generation::GenerationConfig},
+ prelude::Error,
+};
#[uzu_config(super::ModelConfig)]
pub struct LanguageModelConfig {
pub decoder_config: DecoderConfig,
pub generation_config: GenerationConfig,
}
+
+impl LanguageModelConfig {
+ pub fn new(model_path: &Path) -> Result<LanguageModelConfig, Error> {
+ let config_path = model_path.join("config.json");
+ let config_file = File::open(&config_path)?;
+ let model_config: LanguageModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
+ Ok(model_config)
+ }
+}
diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rs
index ebbafaa8b..101b9b5b5 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator.rs
@@ -1,4 +1,10 @@
-use std::{any::Any, iter::repeat_n, ops::Range, path::Path, time::Instant};
+use std::{
+ any::Any,
+ iter::repeat_n,
+ ops::Range,
+ path::Path,
+ time::{Duration, Instant},
+};
use itertools::{Either, Itertools, izip};
@@ -25,17 +31,17 @@ use crate::{
parameter::{ConfigResolvableValue, ResolvableValue, SamplingMethod},
types::Error,
},
- trie::{TrieCreationConfig, TrieNode},
+ trie::{FlatTrie, TrieCreationConfig, TrieNode},
utils::pointers::SendPtr,
};
#[derive(Debug, Clone)]
-struct Task<'a> {
- token_ids: &'a [u64],
- token_subtrie_ranges: Option<&'a [[u32; 3]]>,
- token_positions: &'a [usize],
- token_bitmask: Option<&'a [u32]>,
- token_seeds: &'a [u64],
+pub struct Task {
+ token_ids: Box<[u64]>,
+ token_subtrie_ranges: Option<Box<[[u32; 3]]>>,
+ token_positions: Box<[usize]>,
+ token_bitmask: Option<Box<[u32]>>,
+ token_seeds: Box<[u64]>,
active_row_count: usize,
sampling_start: usize,
sampling_length: usize,
@@ -54,6 +60,13 @@ struct InFlightForwardPass<B: Backend> {
pending: Pending<B>,
}
+pub struct RunModelResult<B: Backend> {
+ pub sampling_output: Option<Allocation<B>>,
+ pub cpu_run_time: f64,
+ #[allow(unused)]
+ pub gpu_run_time: Duration,
+}
+
pub struct LanguageModelGenerator<B: Backend> {
pub decoding_config: DecodingConfig,
pub tokens: Vec<u64>,
@@ -267,19 +280,18 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
let _ = last_sampling_output.take();
let task = Task {
- token_ids: &step_token_ids,
- token_subtrie_ranges: step_token_subtrie_ranges.as_deref(),
- token_positions: &step_token_positions,
- token_bitmask: step_token_bitmask.as_deref(),
- token_seeds: &step_token_seeds,
+ token_ids: step_token_ids,
+ token_subtrie_ranges: step_token_subtrie_ranges,
+ token_positions: step_token_positions,
+ token_bitmask: step_token_bitmask,
+ token_seeds: step_token_seeds,
active_row_count,
sampling_start,
sampling_length,
is_prefilling: !should_sample_after_step,
};
- let (sampling_output, run_time) = self.run_model(task, sampling_method)?;
-
+ let run_result = self.run_model(task, sampling_method)?;
if should_capture {
self.gpu_capture
.stop_capture(&self.context.context, "prefill")
@@ -303,8 +315,8 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
}
last_sampling_length = sampling_length;
- last_sampling_output = sampling_output;
- run_times.push(run_time);
+ last_sampling_output = run_result.sampling_output;
+ run_times.push(run_result.cpu_run_time);
}
let final_sampling_output = last_sampling_output;
@@ -346,7 +358,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
sampling_method: SamplingMethod,
) -> Result<GenerateResult, Error> {
let speculator = &self.decoding_config.speculator_config.speculator;
-
let suffix_length = self.decoding_config.generate_suffix_length();
let suffix_root = TrieNode::from_speculator(
&self.tokens,
@@ -356,61 +367,17 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
&TrieCreationConfig::default(),
suffix_length,
);
-
let flat_trie = suffix_root.linearize();
- let active_row_count = flat_trie.len();
-
- let token_ids =
- flat_trie.token_ids().chain(repeat_n(0, suffix_length - active_row_count)).collect::<Box<[u64]>>();
- let token_subtrie_ranges = flat_trie
- .token_subtrie_ranges()
- .chain(repeat_n([u32::MAX, u32::MAX, u32::MAX], suffix_length - active_row_count))
- .collect::<Box<[[u32; 3]]>>();
-
- let token_bitmask: Option<Box<[u32]>> = compiled_grammar.is_some().then(|| {
- let single_token_bitmask_size = self.context.model_shape.bitmask_shape(1)[1];
- flat_trie
- .token_masks()
- .chain(repeat_n(None, suffix_length - active_row_count))
- .flat_map(|mask| match mask {
- Some(mask) => Either::Left(
- mask.iter()
- .copied()
- .take(single_token_bitmask_size)
- .chain(repeat_n(0u32, single_token_bitmask_size.saturating_sub(mask.len()))),
- ),
- None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),
- })
- .collect::<Box<[u32]>>()
- });
-
- let start_position = self.tokens.len() - 1;
- let token_positions = flat_trie
- .token_positions()
- .map(|trie_position| start_position + trie_position)
- .chain(repeat_n(INVALID_POSITION, suffix_length - active_row_count))
- .collect::<Box<[usize]>>();
-
- let token_seeds =
- flat_trie.token_seeds().chain(repeat_n(0, suffix_length - active_row_count)).collect::<Box<[u64]>>();
-
- let task = Task {
- token_ids: &token_ids,
- token_subtrie_ranges: Some(&token_subtrie_ranges),
- token_positions: &token_positions,
- token_bitmask: token_bitmask.as_deref(),
- token_seeds: &token_seeds,
- active_row_count,
- sampling_start: 0,
- sampling_length: active_row_count,
- is_prefilling: false,
- };
+ let task = self.get_generate_task(&flat_trie, compiled_grammar.is_some());
+ let active_row_count = task.active_row_count;
let sampling_length = task.sampling_length;
- let (sampling_output, run_time) = self.run_model(task, sampling_method)?;
- let sampled_tokens =
- self.read_sampling_output(sampling_output.as_ref().expect("sampling output must exist"), sampling_length)?;
+ let run_result = self.run_model(task, sampling_method)?;
+ let sampled_tokens = self.read_sampling_output(
+ run_result.sampling_output.as_ref().expect("sampling output must exist"),
+ sampling_length,
+ )?;
let (accepted_tokens, accepted_token_indices) = flat_trie.accept(&sampled_tokens, compiled_grammar);
let speculator_proposed = active_row_count.saturating_sub(1);
@@ -423,7 +390,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
Ok(GenerateResult {
tokens: accepted_tokens,
- forwardpass_duration: run_time,
+ forwardpass_duration: run_result.cpu_run_time,
speculator_proposed,
speculator_accepted,
})
@@ -469,11 +436,11 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
let token_seed = self.context.async_buffers.seeds.as_slice::<u64>()[pass_idx];
let task = Task {
- token_ids: &[last_token],
+ token_ids: Box::new([last_token]),
token_subtrie_ranges: None,
- token_positions: &[token_position],
+ token_positions: Box::new([token_position]),
token_bitmask: None,
- token_seeds: &[0], // Ignored, using async buffer
+ token_seeds: Box::new([0]), // Ignored, using async buffer
active_row_count: 1,
sampling_start: 0,
sampling_length: 1,
@@ -685,11 +652,65 @@ impl<B: Backend> LanguageModelGenerator<B> {
})
}
- fn run_model(
+ pub fn get_generate_task(
+ &self,
+ flat_trie: &FlatTrie,
+ has_grammar: bool,
+ ) -> Task {
+ let suffix_length = self.decoding_config.generate_suffix_length();
+ let active_row_count = flat_trie.len();
+
+ let token_ids = flat_trie.token_ids().chain(repeat_n(0, suffix_length - active_row_count)).collect();
+
+ let token_subtrie_ranges = flat_trie
+ .token_subtrie_ranges()
+ .chain(repeat_n([u32::MAX, u32::MAX, u32::MAX], suffix_length - active_row_count))
+ .collect();
+
+ let token_bitmask: Option<Box<[u32]>> = has_grammar.then(|| {
+ let single_token_bitmask_size = self.context.model_shape.bitmask_shape(1)[1];
+ flat_trie
+ .token_masks()
+ .chain(repeat_n(None, suffix_length - active_row_count))
+ .flat_map(|mask| match mask {
+ Some(mask) => Either::Left(
+ mask.iter()
+ .copied()
+ .take(single_token_bitmask_size)
+ .chain(repeat_n(0u32, single_token_bitmask_size.saturating_sub(mask.len()))),
+ ),
+ None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),
+ })
+ .collect::<Box<[u32]>>()
+ });
+
+ let start_position = self.tokens.len() - 1;
+ let token_positions = flat_trie
+ .token_positions()
+ .map(|trie_position| start_position + trie_position)
+ .chain(repeat_n(INVALID_POSITION, suffix_length - active_row_count))
+ .collect();
+
+ let token_seeds = flat_trie.token_seeds().chain(repeat_n(0, suffix_length - active_row_count)).collect();
+
+ Task {
+ token_ids,
+ token_subtrie_ranges: Some(token_subtrie_ranges),
+ token_positions,
+ token_bitmask,
+ token_seeds,
+ active_row_count,
+ sampling_start: 0,
+ sampling_length: active_row_count,
+ is_prefilling: false,
+ }
+ }
+
+ pub fn run_model(
&mut self,
task: Task,
sampling_method: SamplingMethod,
- ) -> Result<(Option<Allocation<B>>, f64), Error> {
+ ) -> Result<RunModelResult<B>, Error> {
let run_start = Instant::now();
let sample = !task.is_prefilling;
let is_prefilling = task.is_prefilling;
@@ -697,7 +718,12 @@ impl<B: Backend> LanguageModelGenerator<B> {
let sampling_start = task.sampling_start;
let sampling_length = task.sampling_length;
let sampling_inputs = sample.then(|| {
- self.create_sampling_inputs(task.sampling_start, task.sampling_length, task.token_seeds, task.token_bitmask)
+ self.create_sampling_inputs(
+ task.sampling_start,
+ task.sampling_length,
+ &task.token_seeds,
+ task.token_bitmask.as_deref(),
+ )
});
let is_first_decode = task.token_ids.len() == 1;
@@ -727,6 +753,7 @@ impl<B: Backend> LanguageModelGenerator<B> {
let pending = encoder.end_encoding().submit();
let completed = pending.wait_until_completed().map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
+ let gpu_run_time = completed.gpu_execution_time();
let ForwardPassResources {
token_inputs,
logits,
@@ -744,7 +771,11 @@ impl<B: Backend> LanguageModelGenerator<B> {
.map_err(|error| Error::CaptureFailed(Box::new(error)))?;
}
- Ok((sampling_output, run_time))
+ Ok(RunModelResult {
+ sampling_output,
+ cpu_run_time: run_time,
+ gpu_run_time,
+ })
}
fn encode_forward_pass_on(
@@ -828,9 +859,9 @@ impl<B: Backend> LanguageModelGenerator<B> {
TokenInputs::new_llm(
self.context.context.as_ref(),
&self.context.model_shape,
- task.token_ids,
- task.token_subtrie_ranges,
- task.token_positions,
+ &task.token_ids,
+ task.token_subtrie_ranges.as_deref(),
+ &task.token_positions,
token_ids_array,
token_positions_array,
task.sampling_start,
diff --git a/crates/backend-uzu/src/lib.rs b/crates/backend-uzu/src/lib.rs
index 2b2ff699a..3f95364e0 100644
--- a/crates/backend-uzu/src/lib.rs
+++ b/crates/backend-uzu/src/lib.rs
@@ -30,6 +30,15 @@ pub use audio::{NanoCodecFsqRuntime, NanoCodecFsqRuntimeConfig};
pub use language_model::gumbel::{gumbel_float, revidx};
pub use utils::{TOOLCHAIN_VERSION, VERSION};
+#[doc(hidden)]
+pub mod _benchmarks {
+ pub use crate::{
+ config::model::language_model::LanguageModelConfig,
+ language_model::{LanguageModelGenerator, language_model_generator::RunModelResult},
+ trie::{TrieCreationConfig, TrieNode},
+ };
+}
+
#[cfg(feature = "tracing")]
pub mod _private {
pub use crate::{
diff --git a/crates/backend-uzu/src/session/chat_session.rs b/crates/backend-uzu/src/session/chat_session.rs
index 965ae91bf..788b51baa 100644
--- a/crates/backend-uzu/src/session/chat_session.rs
+++ b/crates/backend-uzu/src/session/chat_session.rs
@@ -1,7 +1,5 @@
use std::{
any::Any,
- fs::File,
- io::BufReader,
path::PathBuf,
sync::{
Arc,
@@ -81,10 +79,7 @@ impl ChatSession {
return Err(Error::NotEnoughMemory);
}
- let config_path = model_path.join("config.json");
- let config_file = File::open(&config_path)?;
- let model_config: LanguageModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
-
+ let model_config = LanguageModelConfig::new(&model_path)?;
let layers = &model_config.decoder_config.transformer_config.layer_configs;
let has_non_attention_mixer =
layers.iter().any(|layer| !matches!(layer.mixer_config, AnyTokenMixerConfig::AttentionConfig(_)));
diff --git a/crates/backend-uzu/tests/common/path.rs b/crates/backend-uzu/tests/common/path.rs
index de2fb8564..6b1e65601 100644
--- a/crates/backend-uzu/tests/common/path.rs
+++ b/crates/backend-uzu/tests/common/path.rs
@@ -32,3 +32,16 @@ pub fn get_test_weights_path() -> PathBuf {
pub fn get_traces_path() -> PathBuf {
get_test_model_path().join(TRACES_FILE_NAME)
}
+
+#[cfg(target_os = "ios")]
+pub fn ios_set_current_dir() {
+ use objc2_foundation::{NSSearchPathDirectory, NSSearchPathDomainMask, NSSearchPathForDirectoriesInDomains};
+ let paths = NSSearchPathForDirectoriesInDomains(
+ NSSearchPathDirectory(9), // NSDocumentDirectory
+ NSSearchPathDomainMask(1), // NSUserDomainMask
+ true,
+ );
+ if let Some(docs) = paths.firstObject() {
+ let _ = std::env::set_current_dir(docs.to_string());
+ }
+}
diff --git a/crates/backend-uzu/tests/performance/bench_entry.rs b/crates/backend-uzu/tests/performance/bench_entry.rs
new file mode 100644
index 000000000..15072e061
--- /dev/null
+++ b/crates/backend-uzu/tests/performance/bench_entry.rs
@@ -0,0 +1,15 @@
+#![feature(custom_test_frameworks)]
+#![test_runner(crate::bench_runner)]
+
+fn bench_runner(benches: &[&dyn Fn()]) {
+ #[cfg(target_os = "ios")]
+ crate::common::path::ios_set_current_dir();
+ criterion::runner(benches);
+}
+
+use proc_macros::__internal_uzu_bench as uzu_bench;
+
+#[macro_use]
+#[path = "../common/mod.rs"]
+mod common;
+mod language_model;
diff --git a/crates/backend-uzu/tests/performance/kernel/bench_entry.rs b/crates/backend-uzu/tests/performance/kernel/bench_entry.rs
index 07d481836..3d58c86ea 100644
--- a/crates/backend-uzu/tests/performance/kernel/bench_entry.rs
+++ b/crates/backend-uzu/tests/performance/kernel/bench_entry.rs
@@ -3,17 +3,7 @@
fn bench_runner(benches: &[&dyn Fn()]) {
#[cfg(target_os = "ios")]
- {
- use objc2_foundation::{NSSearchPathDirectory, NSSearchPathDomainMask, NSSearchPathForDirectoriesInDomains};
- let paths = NSSearchPathForDirectoriesInDomains(
- NSSearchPathDirectory(9), // NSDocumentDirectory
- NSSearchPathDomainMask(1), // NSUserDomainMask
- true,
- );
- if let Some(docs) = paths.firstObject() {
- let _ = std::env::set_current_dir(docs.to_string());
- }
- }
+ crate::common::path::ios_set_current_dir();
criterion::runner(benches);
}
diff --git a/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs b/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs
new file mode 100644
index 000000000..3bd66874a
--- /dev/null
+++ b/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs
@@ -0,0 +1,61 @@
+use std::time::Duration;
+
+use backend_uzu::{
+ _benchmarks::{LanguageModelConfig, LanguageModelGenerator, RunModelResult, TrieCreationConfig, TrieNode},
+ backends::common::Backend,
+ prelude::{DecodingConfig, SamplingMethod},
+};
+use criterion::{BenchmarkId, Criterion, Throughput};
+
+use crate::{common::path::get_test_model_path, uzu_bench};
+
+fn create_generator<B: Backend>() -> LanguageModelGenerator<B> {
+ let model_path = get_test_model_path();
+ let decoding_config = DecodingConfig::default();
+ let model_config = LanguageModelConfig::new(&model_path).unwrap();
+ LanguageModelGenerator::new(&model_path, decoding_config, &model_config).unwrap()
+}
+
+fn run_generator<B: Backend>(
+ generator: &mut LanguageModelGenerator<B>,
+ tokens: &[u64],
+) -> RunModelResult<B> {
+ generator.tokens = tokens.to_vec();
+ let speculator = &generator.decoding_config.speculator_config.speculator;
+ let suffix_length = generator.decoding_config.generate_suffix_length();
+ let suffix_root = TrieNode::from_speculator(
+ &generator.tokens,
+ &generator.context.seed,
+ None,
+ speculator.as_ref(),
+ &TrieCreationConfig::default(),
+ suffix_length,
+ );
+ let flat_trie = suffix_root.linearize();
+
+ let task = generator.get_generate_task(&flat_trie, false);
+ generator.run_model(task, SamplingMethod::Greedy).unwrap()
+}
+
+#[uzu_bench]
+fn bench_forward_pass(c: &mut Criterion) {
+ // Empty prompt first decode: the generate path requires one seed token.
+ let tokens: Vec<u64> = vec![0];
+ for_each_non_cpu_backend!(|B| {
+ let mut group = c.benchmark_group("Forward pass");
+ group.sample_size(10);
+ group.throughput(Throughput::Elements(tokens.len() as u64));
+ group.bench_function(BenchmarkId::from_parameter("empty prompt first decode"), |b| {
+ b.iter_custom(|n_iters| {
+ let mut total_duration = Duration::from_secs(0);
+ for _ in 0..n_iters {
+ let mut generator = create_generator::<B>();
+ let result = run_generator(&mut generator, &tokens);
+ total_duration += result.gpu_run_time
+ }
+ total_duration
+ });
+ });
+ group.finish()
+ })
+}
diff --git a/crates/backend-uzu/tests/performance/language_model/mod.rs b/crates/backend-uzu/tests/performance/language_model/mod.rs
new file mode 100644
index 000000000..500674adf
--- /dev/null
+++ b/crates/backend-uzu/tests/performance/language_model/mod.rs
@@ -0,0 +1 @@
+mod language_model_generator_bench;