Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Add cpu kernel (#231)

Aleksandr Golokoz9e1762dac2ff
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index 951b0a513..8860c9265 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -81,6 +81,10 @@ metal-nax = []
tracing = []
audio-runtime = []
+[[test]]
+name = "kernel"
+path = "tests/kernel/mod.rs"
+
[[test]]
name = "moe"
path = "tests/moe/mod.rs"
diff --git a/crates/uzu/src/array.rs b/crates/uzu/src/array.rs
index 9b9b658d8..fd7199515 100644
--- a/crates/uzu/src/array.rs
+++ b/crates/uzu/src/array.rs
@@ -258,6 +258,26 @@ pub trait ArrayContextExt {
array.as_bytes_mut().fill(0);
array
}
+
+ fn create_array_from<T: ArrayElement>(
+ &self,
+ shape: &[usize],
+ data: &[T],
+ label: &str,
+ ) -> Array<Self::Backend> {
+ let size_from_shape: usize = shape.iter().product();
+ assert_eq!(
+ data.len(),
+ size_from_shape,
+ "Shape size {} and data size {} are not equal",
+ shape.len(),
+ data.len()
+ );
+
+ let mut array = self.create_array_uninitialized(shape, T::data_type(), label);
+ array.as_slice_mut().copy_from_slice(data);
+ array
+ }
}
impl<C: Context> ArrayContextExt for C {
diff --git a/crates/uzu/src/backends/cpu/kernel/embedding/full_precision_embedding.rs b/crates/uzu/src/backends/cpu/kernel/embedding/full_precision_embedding.rs
index 3d8e27671..9bbde8d67 100644
--- a/crates/uzu/src/backends/cpu/kernel/embedding/full_precision_embedding.rs
+++ b/crates/uzu/src/backends/cpu/kernel/embedding/full_precision_embedding.rs
@@ -15,5 +15,18 @@ pub fn full_precision_embedding_lookup<T: ArrayElement + Float>(
#[allow(unused)] model_dim: u32,
#[allow(unused)] input_scale: f32,
) {
- todo!()
+ for batch_idx in 0..batch_size {
+ let token_id = unsafe { *token_ids.add(batch_idx as usize) };
+ for dim_idx in 0..model_dim {
+ let output_idx = (batch_idx * model_dim + dim_idx) as usize;
+ if token_id >= vocab_size as u64 {
+ unsafe { *output.add(output_idx) = T::zero() };
+ } else {
+ unsafe {
+ let weights_idx = (token_id * (model_dim as u64) + dim_idx as u64) as usize;
+ *output.add(output_idx) = *weights.add(weights_idx) * T::from(input_scale).unwrap();
+ };
+ }
+ }
+ }
}
diff --git a/crates/uzu/tests/common/mod.rs b/crates/uzu/tests/common/mod.rs
index b99e24e92..39f65c6bc 100644
--- a/crates/uzu/tests/common/mod.rs
+++ b/crates/uzu/tests/common/mod.rs
@@ -77,3 +77,19 @@ impl Speculator for RepeatSpeculator {
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 {
+ (|$B:ident| $body:expr) => {{
+ {
+ type $B = uzu::backends::cpu::Cpu;
+ $body
+ }
+ #[cfg(feature = "metal")]
+ {
+ type $B = uzu::backends::metal::Metal;
+ $body
+ }
+ }};
+}
diff --git a/crates/uzu/tests/kernel/full_precision_embedding.rs b/crates/uzu/tests/kernel/full_precision_embedding.rs
new file mode 100644
index 000000000..3786d59e0
--- /dev/null
+++ b/crates/uzu/tests/kernel/full_precision_embedding.rs
@@ -0,0 +1,87 @@
+use std::ops::Deref;
+
+use num_traits::Float;
+use uzu::{
+ ArrayElement,
+ array::ArrayContextExt,
+ backends::common::{Backend, CommandBuffer, Context, Kernels, kernel::FullPrecisionEmbeddingLookupKernel},
+};
+
+struct Input<T: ArrayElement + Float> {
+ token_ids: Box<[u64]>,
+ weights: Box<[T]>,
+ batch_size: usize,
+ vocab_size: usize,
+ model_dim: usize,
+ input_scale: f32,
+}
+
+fn get_test_data() -> (Input<f32>, Vec<f32>) {
+ let vocab_size = 11;
+ let model_dim = 513;
+ let batch_size = 7;
+ let input_scale = 2.0_f32;
+
+ let token_ids: Box<[u64]> = Box::new([3, 7, 1, 10, 0, 5, 8]);
+
+ let weights: Box<[f32]> =
+ (0..vocab_size * model_dim).map(|i| (i as f32 + 1.0) * 0.01).collect::<Vec<_>>().into_boxed_slice();
+
+ let mut expected = Vec::with_capacity(batch_size * model_dim);
+ for &tid in token_ids.iter() {
+ let row_start = tid as usize * model_dim;
+ for j in 0..model_dim {
+ expected.push(weights[row_start + j] * input_scale);
+ }
+ }
+
+ let input = Input {
+ token_ids,
+ weights,
+ batch_size,
+ vocab_size,
+ model_dim,
+ input_scale,
+ };
+
+ (input, expected)
+}
+
+fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
+ let context = B::Context::new().expect("Failed to create Context");
+
+ let kernel =
+ <<B as Backend>::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(&context, T::data_type())
+ .expect("Failed to create FullPrecisionEmbeddingLookupKernel");
+
+ let token_ids_array = context.create_array_from(&[input.batch_size], &input.token_ids, "");
+ let weights_array = context.create_array_from(&[input.vocab_size, input.model_dim], &input.weights, "");
+ let output_array = context.create_array_uninitialized(&[input.batch_size, input.model_dim], T::data_type(), "");
+
+ let mut command_buffer = context.create_command_buffer().expect("Failed to get command buffer");
+ command_buffer.with_compute_encoder(|encoder| {
+ kernel.encode(
+ token_ids_array.buffer().borrow().deref(),
+ weights_array.buffer().borrow().deref(),
+ output_array.buffer().borrow().deref(),
+ input.batch_size as u32,
+ input.vocab_size as u32,
+ input.model_dim as u32,
+ input.input_scale,
+ encoder,
+ );
+ });
+ command_buffer.submit();
+ command_buffer.wait_until_completed();
+
+ output_array.as_slice().to_vec()
+}
+
+#[test]
+fn test() {
+ let (input, expected) = get_test_data();
+ for_each_backend!(|B| {
+ let output = get_output::<f32, B>(&input);
+ assert_eq!(output, expected, "Results are not equals for backend {}", std::any::type_name::<B>());
+ });
+}
diff --git a/crates/uzu/tests/kernel/mod.rs b/crates/uzu/tests/kernel/mod.rs
new file mode 100644
index 000000000..199b69466
--- /dev/null
+++ b/crates/uzu/tests/kernel/mod.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+#[path = "../common/mod.rs"]
+mod common;
+
+#[path = "full_precision_embedding.rs"]
+mod full_precision_embedding;