Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Support partial RoPE (#268)

CCYeha68698ad7b9c
diff --git a/crates/uzu/src/backends/cpu/kernel/rope/rope.rs b/crates/uzu/src/backends/cpu/kernel/rope/rope.rs
index 21e0c84bd..3603a5307 100644
--- a/crates/uzu/src/backends/cpu/kernel/rope/rope.rs
+++ b/crates/uzu/src/backends/cpu/kernel/rope/rope.rs
@@ -32,22 +32,24 @@ pub fn rope<T: ArrayElement + Float>(
rotated_queries: *mut T,
rotated_keys: *mut T,
head_dim: u32,
+ rope_dim: u32,
num_heads: u32,
num_groups: u32,
suffix_length: u32,
max_sequence_length: u32,
) {
- if head_dim & 1 != 0 || num_heads % num_groups != 0 {
+ if num_groups == 0 || head_dim & 1 != 0 || rope_dim & 1 != 0 || rope_dim > head_dim || num_heads % num_groups != 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_dim = head_dim / 2;
+ let half_rope_dim = rope_dim / 2;
let total_heads = num_heads + 2 * num_groups;
let heads_per_group = num_heads / num_groups;
@@ -62,14 +64,16 @@ pub fn rope<T: ArrayElement + Float>(
raw_position
};
- for dim_index in 0..head_dim {
- let cos_val = unsafe { *cosines.add(absolute_position * head_dim + dim_index) };
- let sin_val = unsafe { *sines.add(absolute_position * head_dim + dim_index) };
+ // Rotated dimensions: apply RoPE to dims 0..rope_dim
+ for dim_index in 0..rope_dim {
+ let cos_val = unsafe { *cosines.add(absolute_position * rope_dim + dim_index) };
+ let sin_val = unsafe { *sines.add(absolute_position * rope_dim + dim_index) };
// Query rotation
let q_val =
unsafe { *qkv.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index) };
- let q_paired = get_paired_val(qkv, dim_index, half_dim, token_index, total_heads, head_dim, head_index);
+ let q_paired =
+ get_paired_val(qkv, dim_index, half_rope_dim, token_index, total_heads, head_dim, head_index);
let q_result = q_val * cos_val + q_paired * sin_val;
unsafe {
*rotated_queries.add(head_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
@@ -82,8 +86,15 @@ pub fn rope<T: ArrayElement + Float>(
let k_val = unsafe {
*qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index)
};
- let k_paired =
- get_paired_val(qkv, dim_index, half_dim, token_index, total_heads, head_dim, key_head_index);
+ let k_paired = get_paired_val(
+ qkv,
+ dim_index,
+ half_rope_dim,
+ token_index,
+ total_heads,
+ head_dim,
+ key_head_index,
+ );
let k_result = k_val * cos_val + k_paired * sin_val;
unsafe {
*rotated_keys
@@ -92,6 +103,27 @@ pub fn rope<T: ArrayElement + Float>(
}
}
}
+
+ // Pass-through dimensions: copy dims rope_dim..head_dim unchanged
+ for dim_index in rope_dim..head_dim {
+ let q_val =
+ unsafe { *qkv.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index) };
+ unsafe {
+ *rotated_queries.add(head_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
+ q_val;
+ }
+
+ if 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
+ .add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) = k_val;
+ }
+ }
+ }
}
}
}
diff --git a/crates/uzu/src/backends/metal/kernel/rope/rope.metal b/crates/uzu/src/backends/metal/kernel/rope/rope.metal
index 5f6274e14..dca7edd39 100644
--- a/crates/uzu/src/backends/metal/kernel/rope/rope.metal
+++ b/crates/uzu/src/backends/metal/kernel/rope/rope.metal
@@ -23,12 +23,13 @@ template <typename T>
VARIANTS(T, float, half, bfloat)
PUBLIC KERNEL(Rope)(
device const T* qkv, // [suffix_len, (num_heads + 2*num_groups) * head_dim]
- device const T* cosines, // [max_seq_len, head_dim]
- device const T* sines, // [max_seq_len, head_dim]
+ device const T* cosines, // [max_seq_len, rope_dim]
+ device const T* sines, // [max_seq_len, rope_dim]
device const int* token_positions, // [suffix_len] - actual token positions
device T* rotated_queries, // [num_heads, suffix_len, head_dim]
- device T* rotated_keys, // [num_heads, suffix_len, head_dim]
+ device T* rotated_keys, // [num_groups, suffix_len, head_dim]
constant uint& head_dim,
+ constant uint& rope_dim,
constant uint& num_heads,
constant uint& num_groups,
constant uint& suffix_length,
@@ -42,6 +43,12 @@ PUBLIC KERNEL(Rope)(
return;
if (head_dim & 1)
return;
+ if (rope_dim & 1)
+ return;
+ if (rope_dim > head_dim)
+ return;
+ if (num_groups == 0)
+ return;
if (num_heads % num_groups != 0)
return;
@@ -49,59 +56,68 @@ PUBLIC KERNEL(Rope)(
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 raw_position = token_positions[token_index];
const uint absolutePosition =
raw_position > max_sequence_length ? 0 : raw_position;
-
- const uint half_dimension = head_dim / 2;
+ const uint half_rope_dim = rope_dim / 2;
TensorView3D<const T> qkv_tensor_view =
TensorView3D<const T>(qkv).shaped(suffix_length, total_heads, head_dim);
TensorView2D<const T> cosines_tensor_view =
- TensorView2D<const T>(cosines).shaped(max_sequence_length, head_dim);
+ TensorView2D<const T>(cosines).shaped(max_sequence_length, rope_dim);
TensorView2D<const T> sines_tensor_view =
- TensorView2D<const T>(sines).shaped(max_sequence_length, head_dim);
+ TensorView2D<const T>(sines).shaped(max_sequence_length, rope_dim);
TensorView3D<T> rotated_queries_tensor_view =
TensorView3D<T>(rotated_queries)
.shaped(num_heads, suffix_length, head_dim);
TensorView3D<T> rotated_keys_tensor_view =
TensorView3D<T>(rotated_keys).shaped(num_groups, suffix_length, head_dim);
- const T cos_val = cosines_tensor_view(absolutePosition, dimension_index);
- const T sin_val = sines_tensor_view(absolutePosition, dimension_index);
+ uint first_head_in_group = group_index * (num_heads / num_groups);
/* ---------- QUERIES ---------- */
- T queryResult = applyRopeTransform(
- qkv_tensor_view,
- token_index,
- head_index,
- dimension_index,
- half_dimension,
- cos_val,
- sin_val
- );
- rotated_queries_tensor_view(head_index, token_index, dimension_index) =
- queryResult;
+ if (dimension_index < rope_dim) {
+ const T cos_val = cosines_tensor_view(absolutePosition, dimension_index);
+ const T sin_val = sines_tensor_view(absolutePosition, dimension_index);
- /* ---------- KEYS & VALUES (only first head of each group processes)
- * ---------- */
- uint first_head_in_group = group_index * (num_heads / num_groups);
- if (head_index == first_head_in_group) {
- /* ---------- keys ---------- */
- uint key_head_index =
- num_heads + group_index; // Keys start after all query heads
- T keyResult = applyRopeTransform(
+ T queryResult = applyRopeTransform(
qkv_tensor_view,
token_index,
- key_head_index,
+ head_index,
dimension_index,
- half_dimension,
+ half_rope_dim,
cos_val,
sin_val
);
- rotated_keys_tensor_view(group_index, token_index, dimension_index) =
- keyResult;
+ 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
+ T 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;
+ }
+ } else {
+ rotated_queries_tensor_view(head_index, token_index, dimension_index) =
+ qkv_tensor_view(token_index, head_index, dimension_index);
+
+ 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);
+ }
}
}
\ No newline at end of file
diff --git a/crates/uzu/src/config/attention.rs b/crates/uzu/src/config/attention.rs
index 7198357ed..c5b8cf042 100644
--- a/crates/uzu/src/config/attention.rs
+++ b/crates/uzu/src/config/attention.rs
@@ -22,6 +22,8 @@ pub struct AttentionConfig {
pub has_sinks: bool,
pub has_qkv_biases: bool,
pub has_out_biases: bool,
+ #[serde(default)]
+ pub partial_rope_dim: Option<usize>,
}
#[cfg(test)]
@@ -104,6 +106,7 @@ mod tests {
has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
+ partial_rope_dim: None,
};
let deserialized_config: AttentionConfig = from_str(config_str).unwrap();
diff --git a/crates/uzu/src/config/decoder.rs b/crates/uzu/src/config/decoder.rs
index 1342f94ed..9b5538492 100644
--- a/crates/uzu/src/config/decoder.rs
+++ b/crates/uzu/src/config/decoder.rs
@@ -421,6 +421,7 @@ mod tests {
has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
+ partial_rope_dim: None,
}),
mlp_config: MLPConfig::Dense(DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
diff --git a/crates/uzu/src/config/decoder_layer.rs b/crates/uzu/src/config/decoder_layer.rs
index a1f559a04..a6be7f5a2 100644
--- a/crates/uzu/src/config/decoder_layer.rs
+++ b/crates/uzu/src/config/decoder_layer.rs
@@ -236,6 +236,7 @@ mod tests {
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 {
diff --git a/crates/uzu/src/config/transformer_layer.rs b/crates/uzu/src/config/transformer_layer.rs
index 3735ec991..dd76cf2e6 100644
--- a/crates/uzu/src/config/transformer_layer.rs
+++ b/crates/uzu/src/config/transformer_layer.rs
@@ -164,6 +164,7 @@ mod tests {
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 {
diff --git a/crates/uzu/src/encodable_block/rope.rs b/crates/uzu/src/encodable_block/rope.rs
index 4e3aec68c..edee08bcd 100644
--- a/crates/uzu/src/encodable_block/rope.rs
+++ b/crates/uzu/src/encodable_block/rope.rs
@@ -33,7 +33,7 @@ impl<B: Backend> Rope<B> {
state: &mut ForwardPassState<B>,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<(), B::Error> {
- let (suffix_length, num_heads, head_dim, num_groups, rope_max_seq_len) = {
+ let (suffix_length, num_heads, head_dim, num_groups, rope_dim, rope_max_seq_len) = {
let qkv_binding = state.arrays(&[ArrayId::QKV]);
let qkv_array = qkv_binding[0].borrow();
let suffix_length = qkv_array.shape()[0];
@@ -51,8 +51,9 @@ impl<B: Backend> Rope<B> {
let cos_array = cos_binding[0].borrow();
let cos_shape = cos_array.shape();
let rope_max_seq_len = cos_shape[0];
+ let rope_dim = cos_shape[1];
- (suffix_length, num_heads, head_dim, num_groups, rope_max_seq_len)
+ (suffix_length, num_heads, head_dim, num_groups, rope_dim, rope_max_seq_len)
};
let qkv_buffer_binding = state.arrays(&[ArrayId::QKV]);
@@ -83,6 +84,7 @@ impl<B: Backend> Rope<B> {
rotated_queries.buffer().borrow_mut().deref_mut(),
rotated_keys.buffer().borrow_mut().deref_mut(),
head_dim as u32,
+ rope_dim as u32,
num_heads as u32,
num_groups as u32,
suffix_length as u32,
diff --git a/crates/uzu/src/forward_pass/model_shape.rs b/crates/uzu/src/forward_pass/model_shape.rs
index 12f0a3985..634ce39fe 100644
--- a/crates/uzu/src/forward_pass/model_shape.rs
+++ b/crates/uzu/src/forward_pass/model_shape.rs
@@ -1,6 +1,6 @@
use crate::{
DataType,
- config::{DecoderConfig, DecoderLayerType},
+ config::{DecoderConfig, DecoderLayerType, MixerConfig},
};
#[derive(Debug)]
@@ -25,6 +25,7 @@ pub struct ModelShape {
max_mamba_conv_dim: usize,
max_mamba_state_dim: usize,
max_mamba_kernel_size: usize,
+ max_rope_dim: usize,
}
impl ModelShape {
@@ -73,6 +74,25 @@ impl ModelShape {
max_mamba_kernel_size = max_mamba_kernel_size.max(*kernel_size as usize);
}
}
+ let mut max_rope_dim = 0usize;
+
+ let all_layer_configs = decoder_config
+ .layer_configs
+ .as_ref()
+ .map(|configs| configs.iter().collect::<Vec<_>>())
+ .unwrap_or_else(|| vec![&decoder_config.layer_config; num_layers]);
+
+ for layer_config in &all_layer_configs {
+ if let MixerConfig::Attention(attn) = &layer_config.mixer_config {
+ let hd = attn.head_dim.unwrap_or(decoder_config.head_dim);
+ max_rope_dim = max_rope_dim.max(attn.partial_rope_dim.unwrap_or(hd));
+ }
+ }
+
+ if max_rope_dim == 0 {
+ max_rope_dim = decoder_config.head_dim;
+ }
+
Self {
activation_type,
kv_cache_type: activation_type,
@@ -95,6 +115,7 @@ impl ModelShape {
max_mamba_conv_dim,
max_mamba_state_dim,
max_mamba_kernel_size,
+ max_rope_dim,
}
}
@@ -114,6 +135,10 @@ impl ModelShape {
self.head_dim
}
+ pub fn rope_dim(&self) -> usize {
+ self.max_rope_dim
+ }
+
pub fn num_groups(&self) -> usize {
self.num_groups
}
diff --git a/crates/uzu/src/forward_pass/state/rope_buffers.rs b/crates/uzu/src/forward_pass/state/rope_buffers.rs
index 628e63e12..a6437c86d 100644
--- a/crates/uzu/src/forward_pass/state/rope_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/rope_buffers.rs
@@ -8,9 +8,9 @@ use crate::{
};
pub struct RopeBuffers<B: Backend> {
- /// [rope_max_sequence_length, head_dim]
+ /// [rope_max_sequence_length, rope_dim]
pub cosines: ArrayCell<B>,
- /// [rope_max_sequence_length, head_dim]
+ /// [rope_max_sequence_length, rope_dim]
pub sines: ArrayCell<B>,
}
@@ -19,18 +19,17 @@ impl<B: Backend> RopeBuffers<B> {
context: &B::Context,
model_shape: &ModelShape,
) -> Self {
- let rotated_queries_shape = model_shape.rotated_queries_shape(1);
- let head_dim = rotated_queries_shape[2];
+ let rope_dim = model_shape.rope_dim();
let rope_max_sequence_length = model_shape.context_length();
Self {
cosines: RefCell::new(context.create_array_uninitialized(
- &[rope_max_sequence_length, head_dim],
+ &[rope_max_sequence_length, rope_dim],
model_shape.activation_data_type(),
"rope_buffers_cosines",
)),
sines: RefCell::new(context.create_array_uninitialized(
- &[rope_max_sequence_length, head_dim],
+ &[rope_max_sequence_length, rope_dim],
model_shape.activation_data_type(),
"rope_buffers_sines",
)),
diff --git a/crates/uzu/tests/kernel/rope_test.rs b/crates/uzu/tests/kernel/rope_test.rs
index 453681955..1af978474 100644
--- a/crates/uzu/tests/kernel/rope_test.rs
+++ b/crates/uzu/tests/kernel/rope_test.rs
@@ -25,6 +25,7 @@ struct Input<T: ArrayElement + Float> {
sines: Box<[T]>,
token_positions: Box<[i32]>,
head_dim: u32,
+ rope_dim: u32,
num_heads: u32,
num_groups: u32,
suffix_length: u32,
@@ -35,12 +36,13 @@ fn get_test_data<T: ArrayElement + Float>(
num_heads: u32,
num_groups: u32,
head_dim: u32,
+ rope_dim: u32,
suffix_length: u32,
max_sequence_length: u32,
) -> Input<T> {
let total_heads = (num_heads + 2 * num_groups) as usize;
let qkv_size = suffix_length as usize * total_heads * head_dim as usize;
- let cos_sin_size = max_sequence_length as usize * head_dim as usize;
+ let cos_sin_size = max_sequence_length as usize * rope_dim as usize;
let mut qkv = vec![T::zero(); qkv_size];
for i in 0..qkv_size {
@@ -65,6 +67,7 @@ fn get_test_data<T: ArrayElement + Float>(
sines: sines.into_boxed_slice(),
token_positions: token_positions.into_boxed_slice(),
head_dim,
+ rope_dim,
num_heads,
num_groups,
suffix_length,
@@ -80,7 +83,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
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;
- let cos_sin_len = input.max_sequence_length as usize * input.head_dim as usize;
+ let cos_sin_len = input.max_sequence_length as usize * input.rope_dim as usize;
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;
@@ -100,6 +103,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
rotated_queries_array.buffer().borrow_mut().deref_mut(),
rotated_keys_array.buffer().borrow_mut().deref_mut(),
input.head_dim,
+ input.rope_dim,
input.num_heads,
input.num_groups,
input.suffix_length,
@@ -132,30 +136,40 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {
fn test_basic<T: ArrayElement + Float + Debug + Display>() {
// Typical GQA config: 32 query heads, 8 KV groups, head_dim=128, 4 tokens
- let input = get_test_data::<T>(32, 8, 128, 4, 512);
+ let input = get_test_data::<T>(32, 8, 128, 128, 4, 512);
test_internal(&input);
}
fn test_mha<T: ArrayElement + Float + Debug + Display>() {
// MHA: num_heads == num_groups
- let input = get_test_data::<T>(8, 8, 64, 2, 256);
+ let input = get_test_data::<T>(8, 8, 64, 64, 2, 256);
test_internal(&input);
}
fn test_single_token<T: ArrayElement + Float + Debug + Display>() {
// Single token (decode)
- let input = get_test_data::<T>(16, 4, 64, 1, 1024);
+ let input = get_test_data::<T>(16, 4, 64, 64, 1, 1024);
test_internal(&input);
}
fn test_small<T: ArrayElement + Float + Debug + Display>() {
// Minimal config
- let input = get_test_data::<T>(2, 1, 4, 1, 8);
+ let input = get_test_data::<T>(2, 1, 4, 4, 1, 8);
+ test_internal(&input);
+}
+
+fn test_partial_rope_basic<T: ArrayElement + Float + Debug + Display>() {
+ let input = get_test_data::<T>(32, 8, 128, 64, 4, 512);
+ test_internal(&input);
+}
+
+fn test_partial_rope_small<T: ArrayElement + Float + Debug + Display>() {
+ let input = get_test_data::<T>(2, 1, 8, 4, 1, 8);
test_internal(&input);
}
fn test_nonzero_positions<T: ArrayElement + Float + Debug + Display>() {
- let mut input = get_test_data::<T>(4, 2, 8, 3, 64);
+ let mut input = get_test_data::<T>(4, 2, 8, 8, 3, 64);
input.token_positions = vec![10, 11, 12].into_boxed_slice();
test_internal(&input);
}
@@ -227,3 +241,13 @@ fn test_single_token_bf16() {
fn test_small_bf16() {
test_small::<bf16>();
}
+
+#[test]
+fn test_partial_rope_basic_f32() {
+ test_partial_rope_basic::<f32>();
+}
+
+#[test]
+fn test_partial_rope_small_f32() {
+ test_partial_rope_small::<f32>();
+}