A high-performance inference engine for AI models
Support query-only rope (#467)
CCYeh12a67a9e9283
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs b/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rsindex 76a125e9a..85c03aced 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs@@ -35,28 +35,33 @@ pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(sines: *const RopeT,token_positions: *const i32,rotated_queries: *mut ElementT,- rotated_keys: *mut ElementT,+ #[optional(!query_only)] rotated_keys: Option<*mut ElementT>,head_dim: u32,rope_dim: u32,num_heads: u32,- num_groups: u32,+ #[optional(!query_only)] num_groups: Option<u32>,suffix_length: u32,max_sequence_length: u32,+ #[specialize] query_only: bool,) {- if num_groups == 0 || head_dim & 1 != 0 || rope_dim & 1 != 0 || rope_dim > head_dim || num_heads % num_groups != 0 {+ // Query-only projections carry no K/V heads, i.e. num_groups == 0.+ let num_groups = num_groups.unwrap_or(0) as usize;+ if head_dim & 1 != 0 || rope_dim & 1 != 0 || rope_dim > head_dim {+ return;+ }+ if !query_only && (num_groups == 0 || num_heads % num_groups as u32 != 0) {return;}let head_dim = head_dim as usize;let rope_dim = rope_dim as usize;let num_heads = num_heads as usize;- let num_groups = num_groups as usize;let suffix_length = suffix_length as usize;let max_sequence_length = max_sequence_length as usize;let half_rope_dim = rope_dim / 2;let total_heads = num_heads + 2 * num_groups;- let heads_per_group = num_heads / num_groups;+ let heads_per_group = num_heads / num_groups.max(1);for head_index in 0..num_heads {let group_index = head_index / heads_per_group;@@ -88,8 +93,8 @@ pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(ElementT::from(q_result).unwrap();}- // Key rotation (only first head in each group)- if head_index == group_index * heads_per_group {+ // Key rotation (fused only; first head of each group)+ if !query_only && head_index == group_index * heads_per_group {let key_head_index = num_heads + group_index;let k_val = unsafe {(*qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index))@@ -108,6 +113,7 @@ pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(let k_result = k_val * cos_val + k_paired * sin_val;unsafe {*rotated_keys+ .unwrap().add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) =ElementT::from(k_result).unwrap();}@@ -123,13 +129,14 @@ pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(q_val;}- if head_index == group_index * heads_per_group {+ if !query_only && head_index == group_index * heads_per_group {let key_head_index = num_heads + group_index;let k_val = unsafe {*qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index)};unsafe {*rotated_keys+ .unwrap().add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) = k_val;}}diff --git a/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal b/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metalindex f3bb1f7ce..b596ba19d 100644--- a/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal@@ -24,18 +24,19 @@ template <typename ElementT, typename RopeT>VARIANTS(ElementT, float, half, bfloat)VARIANTS(RopeT, float, half, bfloat)PUBLIC KERNEL(Rope)(- device const ElementT* qkv, // [suffix_len, (num_heads + 2*num_groups) * head_dim]+ device const ElementT* qkv, // [suffix_len, total_heads, head_dim]device const RopeT* cosines, // [max_seq_len, rope_dim]device const RopeT* sines, // [max_seq_len, rope_dim]- device const int* token_positions, // [suffix_len] - actual token positions- device ElementT* rotated_queries, // [num_heads, suffix_len, head_dim]- device ElementT* rotated_keys, // [num_groups, suffix_len, head_dim]+ device const int* token_positions, // [suffix_len]+ device ElementT* rotated_queries, // [num_heads, suffix_len, head_dim]+ device ElementT* rotated_keys OPTIONAL(!query_only),constant uint& head_dim,constant uint& rope_dim,constant uint& num_heads,- constant uint& num_groups,+ constant uint& num_groups OPTIONAL(!query_only),constant uint& suffix_length,constant uint& max_sequence_length,+ const bool query_only SPECIALIZE,const uint head_index AXIS(num_heads, 1),const uint token_index AXIS(suffix_length, 1),const uint dimension_index AXIS(head_dim, 128)@@ -49,19 +50,13 @@ PUBLIC KERNEL(Rope)(return;if (rope_dim > head_dim)return;- if (num_groups == 0)- return;- if (num_heads % num_groups != 0)+ if (!query_only && (num_groups == 0 || num_heads % num_groups != 0))return;- const uint group_index =- head_index /- (num_heads / num_groups); // which KV group this head belongs to- const uint total_heads = num_heads + 2 * num_groups;- // Use actual token position from buffer+ const uint total_heads = query_only ? num_heads : num_heads + 2 * num_groups;const uint raw_position = token_positions[token_index];- const uint absolutePosition =- raw_position > max_sequence_length ? 0 : raw_position;+ const uint absolute_position =+ raw_position >= max_sequence_length ? 0 : raw_position;const uint half_rope_dim = rope_dim / 2;TensorView3D<const ElementT> qkv_tensor_view =@@ -74,56 +69,56 @@ PUBLIC KERNEL(Rope)(TensorView3D<ElementT> rotated_queries_tensor_view =TensorView3D<ElementT>(rotated_queries).shaped(num_heads, suffix_length, head_dim);- TensorView3D<ElementT> rotated_keys_tensor_view =- TensorView3D<ElementT>(rotated_keys)- .shaped(num_groups, suffix_length, head_dim);-- uint first_head_in_group = group_index * (num_heads / num_groups);- /* ---------- QUERIES ---------- */if (dimension_index < rope_dim) {const float cos_val =- float(cosines_tensor_view(absolutePosition, dimension_index));+ float(cosines_tensor_view(absolute_position, dimension_index));const float sin_val =- float(sines_tensor_view(absolutePosition, dimension_index));-- ElementT queryResult = applyRopeTransform(- qkv_tensor_view,- token_index,- head_index,- dimension_index,- half_rope_dim,- cos_val,- sin_val- );+ float(sines_tensor_view(absolute_position, dimension_index));rotated_queries_tensor_view(head_index, token_index, dimension_index) =- queryResult;-- /* ---------- KEYS (only first head of each group processes) ---------- */- if (head_index == first_head_in_group) {- uint key_head_index =- num_heads + group_index; // Keys start after all query heads- ElementT keyResult = applyRopeTransform(- qkv_tensor_view,- token_index,- key_head_index,- dimension_index,- half_rope_dim,- cos_val,- sin_val- );- rotated_keys_tensor_view(group_index, token_index, dimension_index) =- keyResult;- }+ applyRopeTransform(+ qkv_tensor_view,+ token_index,+ head_index,+ dimension_index,+ half_rope_dim,+ cos_val,+ sin_val+ );} else {rotated_queries_tensor_view(head_index, token_index, dimension_index) =qkv_tensor_view(token_index, head_index, dimension_index);+ }++ if (query_only)+ return;- if (head_index == first_head_in_group) {- uint key_head_index =- num_heads + group_index; // Keys start after all query heads- rotated_keys_tensor_view(group_index, token_index, dimension_index) =- qkv_tensor_view(token_index, key_head_index, dimension_index);- }+ const uint heads_per_group = num_heads / num_groups;+ const uint group_index = head_index / heads_per_group;+ if (head_index != group_index * heads_per_group)+ return;++ TensorView3D<ElementT> rotated_keys_tensor_view =+ TensorView3D<ElementT>(rotated_keys)+ .shaped(num_groups, suffix_length, head_dim);+ const uint key_head_index = num_heads + group_index;+ if (dimension_index < rope_dim) {+ const float cos_val =+ float(cosines_tensor_view(absolute_position, dimension_index));+ const float sin_val =+ float(sines_tensor_view(absolute_position, dimension_index));+ rotated_keys_tensor_view(group_index, token_index, dimension_index) =+ applyRopeTransform(+ qkv_tensor_view,+ token_index,+ key_head_index,+ dimension_index,+ half_rope_dim,+ cos_val,+ sin_val+ );+ } else {+ rotated_keys_tensor_view(group_index, token_index, dimension_index) =+ qkv_tensor_view(token_index, key_head_index, dimension_index);}}diff --git a/crates/backend-uzu/src/encodable_block/rope.rs b/crates/backend-uzu/src/encodable_block/rope.rsindex ef52eadee..736088392 100644--- a/crates/backend-uzu/src/encodable_block/rope.rs+++ b/crates/backend-uzu/src/encodable_block/rope.rs@@ -25,6 +25,7 @@ impl<B: Backend> Rope<B> {context,model_shape.data_type,model_shape.rope_data_type,+ false,)?,data_type: model_shape.data_type,})@@ -54,11 +55,11 @@ impl<B: Backend> Rope<B> {sines,token_positions,&mut rotated_queries,- &mut rotated_keys,+ Some(&mut rotated_keys),head_dim as u32,rope_dim as u32,num_heads as u32,- num_groups as u32,+ Some(num_groups as u32),suffix_length as u32,rope_max_seq_len as u32,encoder,diff --git a/crates/backend-uzu/tests/unit/kernel/rope_test.rs b/crates/backend-uzu/tests/unit/kernel/rope_test.rsindex 4a3460c53..98d183715 100644--- a/crates/backend-uzu/tests/unit/kernel/rope_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/rope_test.rs@@ -68,13 +68,17 @@ fn get_test_data<T: ArrayElement + Float>(}}-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>, Vec<T>) {+fn get_output<T: ArrayElement + Float, B: Backend>(+ input: &Input<T>,+ query_only: bool,+) -> (Vec<T>, Option<Vec<T>>) {let context = B::Context::new().expect("Failed to create Context");let element_data_type = T::data_type();let rope_data_type = DataType::F32;- let kernel = <<B as Backend>::Kernels as Kernels>::RopeKernel::new(&context, element_data_type, rope_data_type)- .expect("Failed to create RopeKernel");+ let kernel =+ <<B as Backend>::Kernels as Kernels>::RopeKernel::new(&context, element_data_type, rope_data_type, query_only)+ .expect("Failed to create RopeKernel");let total_heads = (input.num_heads + 2 * input.num_groups) as usize;let qkv_len = input.suffix_length as usize * total_heads * input.head_dim as usize;@@ -82,7 +86,11 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,let queries_len = input.num_heads as usize * input.suffix_length as usize * input.head_dim as usize;let keys_len = input.num_groups as usize * input.suffix_length as usize * input.head_dim as usize;- let qkv_array = context.create_array_from(&[qkv_len], &input.qkv);+ let qkv_array = if query_only {+ context.create_array_from(&[queries_len], &input.qkv[..queries_len])+ } else {+ context.create_array_from(&[qkv_len], &input.qkv)+ };let cosines_array = context.create_array_from(&[cos_sin_len], &input.cosines);let sines_array = context.create_array_from(&[cos_sin_len], &input.sines);let token_positions_array = context.create_array_from(&[input.suffix_length as usize], &input.token_positions);@@ -96,21 +104,32 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,sines_array.allocation(),token_positions_array.allocation(),&mut rotated_queries,- &mut rotated_keys,+ if query_only {+ None::<&mut backend_uzu::backends::common::Allocation<B>>+ } else {+ Some(&mut rotated_keys)+ },input.head_dim,input.rope_dim,input.num_heads,- input.num_groups,+ if query_only {+ None+ } else {+ Some(input.num_groups)+ },input.suffix_length,input.max_sequence_length,&mut encoder,);encoder.end_encoding().submit().wait_until_completed().unwrap();- (- crate::common::helpers::allocation_to_vec(&rotated_queries),- crate::common::helpers::allocation_to_vec(&rotated_keys),- )+ let queries = crate::common::helpers::allocation_to_vec(&rotated_queries);+ let keys = if query_only {+ None+ } else {+ Some(crate::common::helpers::allocation_to_vec(&rotated_keys))+ };+ (queries, keys)}fn test_internal<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {@@ -120,10 +139,12 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {1e-5};- let (expected_queries, expected_keys) = get_output::<T, Cpu>(input);+ let (expected_queries, expected_keys) = get_output::<T, Cpu>(input, false);+ let expected_keys = expected_keys.expect("full rope returns keys");for_each_non_cpu_backend!(|B| {- let (queries, keys) = get_output::<T, B>(input);+ let (queries, keys) = get_output::<T, B>(input, false);+ let keys = keys.expect("full rope returns keys");let msg = format!("Rope queries test failed with backend={}", std::any::type_name::<B>(),);assert_eq_float::<T>(&expected_queries, &queries, eps, &msg);@@ -172,6 +193,20 @@ fn test_nonzero_positions<T: ArrayElement + Float + Debug + Display>() {test_internal(&input);}+fn test_query_only<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {+ let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {+ 0.02f32+ } else {+ 1e-5+ };+ let (expected, _) = get_output::<T, Cpu>(input, true);+ for_each_non_cpu_backend!(|B| {+ let (actual, _) = get_output::<T, B>(input, true);+ let msg = format!("Rope query-only test failed with backend={}", std::any::type_name::<B>());+ assert_eq_float::<T>(&expected, &actual, eps, &msg);+ });+}+// f32 tests#[uzu_test]fn test_basic_f32() {@@ -198,6 +233,21 @@ fn test_nonzero_positions_f32() {test_nonzero_positions::<f32>();}+#[uzu_test]+fn test_query_only_f32() {+ test_query_only::<f32>(&get_test_data::<f32>(8, 2, 64, 64, 4, 512));+}++#[uzu_test]+fn test_query_only_partial_f32() {+ test_query_only::<f32>(&get_test_data::<f32>(8, 2, 256, 128, 4, 512));+}++#[uzu_test]+fn test_query_only_bf16() {+ test_query_only::<bf16>(&get_test_data::<bf16>(8, 2, 64, 64, 4, 512));+}+// f16 tests#[uzu_test]fn test_basic_f16() {