Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

weaver update

eugeneabd5e696b5fe
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs
index b8d5fc7f2..7d43495ab 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs
@@ -2,6 +2,7 @@ use half::bf16;
use proc_macros::kernel;
use super::attention_single_pass::attention_single_pass;
+use crate::backends::common::gpu_types::weaver::MetadataIdx;
#[kernel(AncestorAttention)]
#[variants(HEAD_DIM, 128)]
@@ -9,6 +10,9 @@ fn ancestor_attention<const HEAD_DIM: u32>(
prefix_kv: *const bf16,
node_kv: *mut bf16,
current_qkv: *const bf16,
+ cosines: *const f32,
+ sines: *const f32,
+ node_metadata: *const u32,
ancestor_indices: *const u32,
ancestor_counts: *const u32,
node_indices: *const u32,
@@ -17,6 +21,7 @@ fn ancestor_attention<const HEAD_DIM: u32>(
prefix_length: u32,
ancestor_stride: u32,
node_capacity: u32,
+ max_depth: u32,
scale: f32,
#[specialize] num_heads: u32,
) {
@@ -30,11 +35,37 @@ fn ancestor_attention<const HEAD_DIM: u32>(
let prefix_length = prefix_length as usize;
let node_capacity = node_capacity as usize;
let last_node = node_capacity.saturating_sub(1);
+ let half_dim = head_dim / 2;
+ let row_count = rows as usize;
- for row in 0..rows as usize {
+ for row in 0..row_count {
unsafe {
let current_row = current_qkv.add(row * qkv_width);
+ let depth = *node_metadata.add(MetadataIdx::Depth as usize * row_count + row);
+ let position = depth.min(max_depth - 1) as usize + 1;
+ let rotate = |component: usize| {
+ let mut rotated = vec![bf16::ZERO; model_dim];
+ for head in 0..num_heads {
+ let base = component * model_dim + head * head_dim;
+ for pair in 0..half_dim {
+ let low = (*current_row.add(base + pair)).to_f32();
+ let high = (*current_row.add(base + half_dim + pair)).to_f32();
+ let index = position * head_dim + pair;
+ let low_cosine = *cosines.add(index);
+ let low_sine = *sines.add(index);
+ let high_cosine = *cosines.add(index + half_dim);
+ let high_sine = *sines.add(index + half_dim);
+ rotated[head * head_dim + pair] = bf16::from_f32(low * low_cosine - high * low_sine);
+ rotated[head * head_dim + half_dim + pair] =
+ bf16::from_f32(high * high_cosine + low * high_sine);
+ }
+ }
+ rotated
+ };
+ let rotated_queries = rotate(0);
+ let rotated_keys = rotate(KEY_COMPONENT);
+
let ancestor_count = *ancestor_counts.add(row) as usize;
let length = prefix_length + ancestor_count + 1;
let mut keys = vec![bf16::ZERO; length * model_dim];
@@ -59,7 +90,7 @@ fn ancestor_attention<const HEAD_DIM: u32>(
);
}
std::ptr::copy_nonoverlapping(
- current_row.add(KEY_COMPONENT * model_dim),
+ rotated_keys.as_ptr(),
keys.as_mut_ptr().add((length - 1) * model_dim),
model_dim,
);
@@ -69,7 +100,7 @@ fn ancestor_attention<const HEAD_DIM: u32>(
model_dim,
);
attention_single_pass::<bf16, HEAD_DIM>(
- current_row,
+ rotated_queries.as_ptr(),
keys.as_ptr(),
values.as_ptr(),
output.add(row * num_heads * head_dim),
@@ -94,11 +125,7 @@ fn ancestor_attention<const HEAD_DIM: u32>(
);
if node_capacity > 0 {
let node = (*node_indices.add(row) as usize).min(last_node);
- std::ptr::copy_nonoverlapping(
- current_row.add(KEY_COMPONENT * model_dim),
- node_kv.add(node * model_dim),
- model_dim,
- );
+ std::ptr::copy_nonoverlapping(rotated_keys.as_ptr(), node_kv.add(node * model_dim), model_dim);
std::ptr::copy_nonoverlapping(
current_row.add(VALUE_COMPONENT * model_dim),
node_kv.add(node_capacity * model_dim + node * model_dim),
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
index e9b8b936e..c67731e6e 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
@@ -43,7 +43,6 @@ impl MatmulKernel for MatmulCpuKernel {
output_data_type,
weights_data_type,
true,
- false,
)?;
Ok(Self {
weights_data_type,
@@ -296,15 +295,7 @@ impl MatmulKernel for MatmulCpuKernel {
self.output_rht.encode_fp_in_place(&mut *d, factors, m, n, encoder);
if let Some(bias) = bias_alloc {
let output_length = m.checked_mul(n).expect("matmul output length must fit in u32");
- self.bias_add.encode(
- None::<&Allocation<Cpu>>,
- bias,
- None::<&Allocation<Cpu>>,
- &mut *d,
- n,
- output_length,
- encoder,
- );
+ self.bias_add.encode(None::<&Allocation<Cpu>>, bias, &mut *d, n, output_length, encoder);
}
}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/tensor_add_bias/tensor_add_bias.rs b/crates/backend-uzu/src/backends/cpu/kernel/tensor_add_bias/tensor_add_bias.rs
index a8bf72eb0..96465c733 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/tensor_add_bias/tensor_add_bias.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/tensor_add_bias/tensor_add_bias.rs
@@ -10,22 +10,15 @@ use crate::array::ArrayElement;
pub fn tensor_add_bias<T: ArrayElement + Float, BiasT: ArrayElement + Float>(
#[optional(!in_place)] input: Option<*const T>,
bias: *const BiasT,
- #[optional(indexed)] bias_row_indices: Option<*const u32>,
output: *mut T,
num_cols: u32,
length: u32,
#[specialize] in_place: bool,
- #[specialize] indexed: bool,
) {
assert_eq!(input.is_none(), in_place);
- assert_eq!(bias_row_indices.is_some(), indexed);
for i in 0usize..(length as usize) {
- let column = i % num_cols as usize;
- let bias_position = match bias_row_indices {
- Some(indices) => unsafe { *indices.add(i / num_cols as usize) as usize * num_cols as usize + column },
- None => column,
- };
+ let bias_position = i % num_cols as usize;
unsafe {
let value: f32 = if let Some(in_data) = input {
num_traits::cast(*in_data.add(i)).unwrap()
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal
index 519d6ec6d..c4f6f655e 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal
@@ -4,6 +4,7 @@
#include "../common/integral_constant.h"
#include "../common/dsl.h"
#include "../common/thread_context.h"
+#include "../weaver/weaver_frontier.h"
using namespace metal;
@@ -55,6 +56,9 @@ PUBLIC KERNEL(AncestorAttention)(
const device bfloat* prefix_kv,
device bfloat* node_kv,
const device bfloat* current_qkv,
+ const device float* cosines,
+ const device float* sines,
+ const device uint* node_metadata,
const device uint* ancestor_indices,
const device uint* ancestor_counts,
const device uint* node_indices,
@@ -63,6 +67,7 @@ PUBLIC KERNEL(AncestorAttention)(
constant uint& prefix_length,
constant uint& ancestor_stride,
constant uint& node_capacity,
+ constant uint& max_depth,
constant float& scale,
const uint num_heads SPECIALIZE,
const ThreadContext thread_context,
@@ -90,7 +95,29 @@ PUBLIC KERNEL(AncestorAttention)(
device bfloat4* node_vectors = (device bfloat4*)node_kv;
const device bfloat4* current_row = (const device bfloat4*)current_qkv + row * qkv_vectors;
- const float4 query = float4(current_row[head_offset]) * scale;
+ // Rotate this node's query and key by its position, here rather than in a
+ // pass of its own. The rotation pairs every channel with one from the other
+ // half of the head, and a thread 16 lanes over already holds that half, so we
+ // ask it directly instead of reading the buffer a second time.
+ static_assert(vectors_per_head == METAL_SIMD_SIZE, "one lane per head vector");
+ const uint depth = node_metadata[uint(MetadataIdx::Depth) * rows + row];
+ const uint rope_position = min(depth, max_depth - 1u) + 1u;
+ const device float4* cosine_row = (const device float4*)(cosines + rope_position * HEAD_DIM);
+ const device float4* sine_row = (const device float4*)(sines + rope_position * HEAD_DIM);
+ const float4 cosine = cosine_row[lane];
+ const float4 sine = sine_row[lane];
+ const bool low_half = lane < (vectors_per_head / 2);
+
+ const float4 raw_query = float4(current_row[head_offset]);
+ const float4 paired_query = simd_shuffle_xor(raw_query, ushort(vectors_per_head / 2));
+ const float4 rotated_query =
+ low_half ? (raw_query * cosine - paired_query * sine) : (raw_query * cosine + paired_query * sine);
+
+ const float4 raw_key = float4(current_row[current_key_offset]);
+ const float4 paired_key = simd_shuffle_xor(raw_key, ushort(vectors_per_head / 2));
+ const float4 rotated_key = low_half ? (raw_key * cosine - paired_key * sine) : (raw_key * cosine + paired_key * sine);
+
+ const float4 query = rotated_query * scale;
// prefix_length >= 1 (the u0 token): seed the online softmax from position 0.
float max_score = simd_sum(dot(query, float4(prefix_vectors[head_offset])));
@@ -124,14 +151,19 @@ PUBLIC KERNEL(AncestorAttention)(
});
}
- attend_qkv<1>(query, current_key_offset, current_value_offset, values, max_score, sum, [&](int) {
- return current_row;
- });
+ const float own_score = simd_sum(dot(query, rotated_key));
+ const float4 own_value = float4(current_row[current_value_offset]);
+ const float own_max = max(max_score, own_score);
+ const float rescale = fast::exp(max_score - own_max);
+ const float own_factor = fast::exp(own_score - own_max);
+ sum = sum * rescale + own_factor;
+ values = values * rescale + own_factor * own_value;
+ max_score = own_max;
if (node_capacity > 0u) {
const uint node = min(node_indices[row], last_node);
- node_vectors[node * model_vectors + head_offset] = current_row[current_key_offset];
+ node_vectors[node * model_vectors + head_offset] = bfloat4(rotated_key);
node_vectors[node_value_offset + node * model_vectors] = current_row[current_value_offset];
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
index 0f6a09979..39b8d5bc1 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -51,7 +51,7 @@ impl GemmKernel {
input_data_type: DataType,
output_data_type: DataType,
) -> Result<Self, MetalError> {
- let bias_add = TensorAddBiasMetalKernel::new(context, output_data_type, weights_data_type, true, false)?;
+ let bias_add = TensorAddBiasMetalKernel::new(context, output_data_type, weights_data_type, true)?;
let output_rht = ActivationTransform::output_rht(context, output_data_type, true)?;
let kernel = Self {
weights_data_type,
@@ -550,15 +550,7 @@ impl GemmKernel {
if let Some(bias) = bias_after_rht {
let output_length = m.checked_mul(n).expect("GEMM output length must fit in u32");
- self.bias_add.encode(
- None::<&Allocation<Metal>>,
- bias,
- None::<&Allocation<Metal>>,
- &mut *d,
- n,
- output_length,
- encoder,
- );
+ self.bias_add.encode(None::<&Allocation<Metal>>, bias, &mut *d, n, output_length, encoder);
}
},
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/tensor_add_bias/tensor_add_bias.metal b/crates/backend-uzu/src/backends/metal/kernel/tensor_add_bias/tensor_add_bias.metal
index 76913bae1..17da4e2ed 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/tensor_add_bias/tensor_add_bias.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/tensor_add_bias/tensor_add_bias.metal
@@ -7,20 +7,16 @@ VARIANTS(BiasT, float, half, bfloat)
PUBLIC KERNEL(TensorAddBias)(
const device T* input OPTIONAL(!in_place),
const device BiasT* bias,
- const device uint* bias_row_indices OPTIONAL(indexed),
device T* output,
constant uint& num_cols,
constant uint& length,
const uint position AXIS(length, 32),
- const bool in_place SPECIALIZE,
- const bool indexed SPECIALIZE
+ const bool in_place SPECIALIZE
) {
if (in_place) {
input = output;
}
- const uint row = position / num_cols;
- const uint column = position % num_cols;
- const ulong bias_position = indexed ? ulong(bias_row_indices[row]) * ulong(num_cols) + ulong(column) : column;
+ const uint bias_position = position % num_cols;
output[position] = static_cast<T>(static_cast<float>(input[position]) + static_cast<float>(bias[bias_position]));
}
diff --git a/crates/backend-uzu/src/config/activation/silu.rs b/crates/backend-uzu/src/config/activation/silu.rs
index 4dbf2ba15..33c5287a3 100644
--- a/crates/backend-uzu/src/config/activation/silu.rs
+++ b/crates/backend-uzu/src/config/activation/silu.rs
@@ -4,3 +4,12 @@ use proc_macros::uzu_config;
pub struct SiLU {
pub alpha: f32,
}
+
+impl Default for SiLU {
+ fn default() -> Self {
+ Self {
+ ty: Default::default(),
+ alpha: 1.0,
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/config/mlp/dense_mlp.rs b/crates/backend-uzu/src/config/mlp/dense_mlp.rs
index 8b85f1871..6c808aa8d 100644
--- a/crates/backend-uzu/src/config/mlp/dense_mlp.rs
+++ b/crates/backend-uzu/src/config/mlp/dense_mlp.rs
@@ -11,3 +11,22 @@ pub struct DenseMLPConfig {
pub gate_clipping: Option<(Option<f32>, Option<f32>)>,
pub up_clipping: Option<(Option<f32>, Option<f32>)>,
}
+
+impl DenseMLPConfig {
+ pub fn unclipped(
+ linear_config: LinearConfig,
+ activation: AnyActivation,
+ has_up_biases: bool,
+ has_down_biases: bool,
+ ) -> Self {
+ Self {
+ ty: Default::default(),
+ linear_config,
+ activation,
+ has_up_biases,
+ has_down_biases,
+ gate_clipping: None,
+ up_clipping: None,
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/config/weaver.rs b/crates/backend-uzu/src/config/weaver.rs
index 48f38cb2f..c106830a1 100644
--- a/crates/backend-uzu/src/config/weaver.rs
+++ b/crates/backend-uzu/src/config/weaver.rs
@@ -1,6 +1,6 @@
use proc_macros::uzu_config;
-use crate::config::{linear::LinearConfig, normalization::NormalizationConfig};
+use crate::config::{linear::LinearConfig, normalization::NormalizationConfig, rope::AnyRoPEConfig};
#[uzu_config]
pub struct WeaverConfig {
@@ -14,4 +14,5 @@ pub struct WeaverConfig {
pub candidate_pool_size: usize,
pub linear_config: LinearConfig,
pub norm_config: NormalizationConfig,
+ pub rope_config: AnyRoPEConfig,
}
diff --git a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
index 2916f6399..ac1a4bd4c 100644
--- a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
+++ b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
@@ -213,9 +213,8 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
let gate_act_mul = <B::Kernels as Kernels>::GatedActMulKernel::new(context, data_type, false, false)
.map_err(PerLayerEmbeddingError::BackendError)?;
- let residual_finalize =
- <B::Kernels as Kernels>::TensorAddBiasKernel::new(context, data_type, data_type, true, false)
- .map_err(PerLayerEmbeddingError::BackendError)?;
+ let residual_finalize = <B::Kernels as Kernels>::TensorAddBiasKernel::new(context, data_type, data_type, true)
+ .map_err(PerLayerEmbeddingError::BackendError)?;
let residual_combine = <B::Kernels as Kernels>::TensorAddScaleKernel::new(context, data_type, true)
.map_err(PerLayerEmbeddingError::BackendError)?;
@@ -251,7 +250,6 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
self.residual_finalize.encode(
None::<&Allocation<B>>,
hidden,
- None::<&Allocation<B>>,
&mut *outputs,
length as u32,
length as u32,
diff --git a/crates/backend-uzu/src/encodable_block/weaver.rs b/crates/backend-uzu/src/encodable_block/weaver.rs
index 57f927a70..082d67f2a 100644
--- a/crates/backend-uzu/src/encodable_block/weaver.rs
+++ b/crates/backend-uzu/src/encodable_block/weaver.rs
@@ -8,11 +8,17 @@ use crate::{
CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx, TreeIdx,
},
kernel::{
- ActivationKernel, AncestorAttentionKernel, AttentionPrepareKernel, TensorAddBiasKernel,
- WeaverFrontierInsertChildrenKernel, WeaverFrontierSelectKernel, WeaverTopChildrenKernel,
+ AncestorAttentionKernel, AttentionPrepareKernel, WeaverFrontierInsertChildrenKernel,
+ WeaverFrontierSelectKernel, WeaverTopChildrenKernel,
},
},
- config::{normalization::NormalizationConfig, weaver::WeaverConfig},
+ config::{
+ activation::{AnyActivation, silu::SiLU},
+ linear::LinearConfig,
+ mlp::{AnyMLPConfig, dense_mlp::DenseMLPConfig},
+ rope::AnyRoPEConfig,
+ weaver::WeaverConfig,
+ },
data_type::DataType,
encodable_block::{
embedding::{Embedding, EmbeddingError},
@@ -20,13 +26,25 @@ use crate::{
mixer::attention::{
AttentionStateType,
core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, AttentionCores},
+ rope::PrecalculatedRoPE,
},
+ mlp::{Mlp, MlpBlockError},
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
},
parameters::{ParameterLoaderError, ParameterTree},
};
const DATA_TYPE: DataType = DataType::BF16;
+const ROPE_DATA_TYPE: DataType = DataType::F32;
+
+fn weaver_mlp_config(linear_config: LinearConfig) -> AnyMLPConfig {
+ AnyMLPConfig::DenseMLPConfig(DenseMLPConfig::unclipped(
+ linear_config,
+ AnyActivation::SiLU(SiLU::default()),
+ true,
+ true,
+ ))
+}
struct TopKChildren<B: Backend> {
token_ids: Allocation<B>,
@@ -114,9 +132,7 @@ pub struct Weaver<B: Backend> {
layers: Box<[WeaverLayer<B>]>,
readout_norm: Normalization<B>,
readout_query_projection: Box<dyn Linear<B>>,
- position_embeddings: Allocation<B>,
- prefix_position_add: <B::Kernels as Kernels>::TensorAddBiasKernel,
- node_position_add: <B::Kernels as Kernels>::TensorAddBiasKernel,
+ rope_config: AnyRoPEConfig,
top_children: <B::Kernels as Kernels>::WeaverTopChildrenKernel,
frontier_select: <B::Kernels as Kernels>::WeaverFrontierSelectKernel,
frontier_insert_children: <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel,
@@ -136,16 +152,14 @@ struct WeaverLayer<B: Backend> {
// MLP
pre_mlp_norm: Normalization<B>,
- up_projection: Box<dyn Linear<B>>,
- activation: <B::Kernels as Kernels>::ActivationKernel,
- down_projection: Box<dyn Linear<B>>,
+ mlp: Box<dyn Mlp<B>>,
// Geometry
attention_scale: f32,
model_dim: usize,
- hidden_dim: usize,
num_heads: usize,
head_dim: usize,
+ max_depth: usize,
}
#[derive(Debug, Error)]
@@ -154,6 +168,8 @@ pub enum WeaverNewError<B: Backend> {
ParameterLoader(#[from] ParameterLoaderError<B>),
#[error("linear error: {0}")]
Linear(#[from] LinearBlockError<B>),
+ #[error("mlp error: {0}")]
+ Mlp(#[from] MlpBlockError<B>),
#[error("normalization error: {0}")]
Normalization(#[from] NormalizationNewError<B>),
#[error("backend error: {0}")]
@@ -164,6 +180,16 @@ pub enum WeaverNewError<B: Backend> {
InvalidHeadConfig,
#[error("candidate_pool_size must be in 1..={max}, got {0}", max = CANDIDATES_MAX)]
InvalidCandidatePoolSize(usize),
+ #[error("rope head_dim {actual} does not match model_dim / num_heads = {expected}")]
+ InvalidRopeHeadDim {
+ expected: usize,
+ actual: usize,
+ },
+ #[error("rope max_sequence_length {actual} is too small for max_depth {max_depth} (needs {max_depth} + 1)")]
+ InvalidRopeLength {
+ max_depth: usize,
+ actual: usize,
+ },
}
#[derive(Debug, Error)]
@@ -191,6 +217,19 @@ impl<B: Backend> Weaver<B> {
if config.candidate_pool_size == 0 || config.candidate_pool_size > CANDIDATES_MAX {
return Err(WeaverNewError::InvalidCandidatePoolSize(config.candidate_pool_size));
}
+ let head_dim = config.model_dim / config.num_heads;
+ if *config.rope_config.head_dim() != head_dim {
+ return Err(WeaverNewError::InvalidRopeHeadDim {
+ expected: head_dim,
+ actual: *config.rope_config.head_dim(),
+ });
+ }
+ if *config.rope_config.max_sequence_length() <= config.max_depth {
+ return Err(WeaverNewError::InvalidRopeLength {
+ max_depth: config.max_depth,
+ actual: *config.rope_config.max_sequence_length(),
+ });
+ }
let token_embedding_norm = Normalization::new(
config.target_embedding_dim,
None,
@@ -221,17 +260,7 @@ impl<B: Backend> Weaver<B> {
)?;
let layer_parameters = parameter_tree.subtree("blocks")?;
let layers = (0..config.num_layers)
- .map(|index| {
- WeaverLayer::new(
- context,
- config.model_dim,
- config.hidden_dim,
- config.num_heads,
- index > 0,
- &config.norm_config,
- &layer_parameters.subtree(&index.to_string())?,
- )
- })
+ .map(|index| WeaverLayer::new(context, config, index > 0, &layer_parameters.subtree(&index.to_string())?))
.collect::<Result<Box<[_]>, WeaverNewError<B>>>()?;
let readout_norm = Normalization::new(
config.model_dim,
@@ -259,16 +288,6 @@ impl<B: Backend> Weaver<B> {
DATA_TYPE,
&parameter_tree.subtree("query_projection")?,
)?;
- let position_embeddings = parameter_tree
- .leaf("position_embeddings")?
- .validate(&[config.max_depth, config.model_dim], DataType::F32)?
- .read_allocation()?;
- let prefix_position_add =
- <B::Kernels as Kernels>::TensorAddBiasKernel::new(context, DATA_TYPE, DataType::F32, true, false)
- .map_err(WeaverNewError::Backend)?;
- let node_position_add =
- <B::Kernels as Kernels>::TensorAddBiasKernel::new(context, DATA_TYPE, DataType::F32, true, true)
- .map_err(WeaverNewError::Backend)?;
let top_children =
<B::Kernels as Kernels>::WeaverTopChildrenKernel::new(context).map_err(WeaverNewError::Backend)?;
let frontier_select =
@@ -283,9 +302,7 @@ impl<B: Backend> Weaver<B> {
layers,
readout_norm,
readout_query_projection,
- position_embeddings,
- prefix_position_add,
- node_position_add,
+ rope_config: config.rope_config.clone(),
top_children,
frontier_select,
frontier_insert_children,
@@ -317,8 +334,10 @@ impl<B: Backend> Weaver<B> {
return Err(WeaverEncodeError::InvalidTreeInput);
}
+ let rope = self.precalculate_rope(encoder).map_err(WeaverEncodeError::Backend)?;
+
let prefix_cache = self
- .encode_prefix(inputs.target_hidden, inputs.draft_hidden, lookahead_count, encoder)
+ .encode_prefix(inputs.target_hidden, inputs.draft_hidden, &rope, lookahead_count, encoder)
.map_err(WeaverEncodeError::Backend)?;
let mut node_cache =
self.create_node_expansion_kv_cache(tree_slot_count, encoder).map_err(WeaverEncodeError::Backend)?;
@@ -419,6 +438,7 @@ impl<B: Backend> Weaver<B> {
&nodes,
&candidates,
&mut node_cache,
+ &rope,
shape.children_per_node,
inputs.target_embedding,
encoder,
@@ -444,10 +464,19 @@ impl<B: Backend> Weaver<B> {
})
}
+ fn precalculate_rope(
+ &self,
+ encoder: &mut Encoder<B>,
+ ) -> Result<PrecalculatedRoPE<B>, B::Error> {
+ let positions = (0..=self.max_depth).collect::<Box<[_]>>();
+ PrecalculatedRoPE::precalculate(&self.rope_config, &positions, encoder)
+ }
+
fn encode_prefix(
&self,
target_hidden: &Allocation<B>,
draft_hidden: &Allocation<B>,
+ rope: &PrecalculatedRoPE<B>,
lookahead_count: usize,
encoder: &mut Encoder<B>,
) -> Result<PrefixKvCache<B>, B::Error> {
@@ -466,16 +495,6 @@ impl<B: Backend> Weaver<B> {
);
let normalized_prefix = self.hidden_state_norm.encode(&prefix_hidden, 0, token_count, None, encoder)?;
let mut residual_input = self.hidden_state_projection.encode(normalized_prefix, token_count, encoder)?;
- let position_elements = lookahead_count * self.model_dim;
- self.prefix_position_add.encode(
- None::<&Allocation<B>>,
- &self.position_embeddings,
- None::<&Allocation<B>>,
- (&mut residual_input, self.model_dim * DATA_TYPE.size_in_bytes()),
- position_elements as u32,
- position_elements as u32,
- encoder,
- );
let (last_layer, preceding_layers) = self.layers.split_last().expect("Weaver must have at least one layer");
let mut residual_state = encoder.allocate_scratch(residual_input.size())?;
let mut prefix_layers = Vec::with_capacity(self.layers.len());
@@ -483,12 +502,14 @@ impl<B: Backend> Weaver<B> {
let PrefixLayerOutput {
mlp_delta,
kv_cache,
- } = layer.encode_prefix_tokens(residual_input, &mut residual_state, token_count, encoder)?;
+ } = layer.encode_prefix_tokens(residual_input, &mut residual_state, rope, token_count, encoder)?;
prefix_layers.push(kv_cache);
residual_input = mlp_delta;
}
prefix_layers.push(
- last_layer.encode_prefix_attention(&residual_input, &mut residual_state, token_count, encoder)?.kv_cache,
+ last_layer
+ .encode_prefix_attention(&residual_input, &mut residual_state, rope, token_count, encoder)?
+ .kv_cache,
);
Ok(PrefixKvCache {
layers: prefix_layers.into_boxed_slice(),
@@ -517,6 +538,7 @@ impl<B: Backend> Weaver<B> {
nodes: &NodeBatch<'_, B>,
candidates: &CandidateBatch<'_, B>,
node_cache: &mut NodeExpansionKvCache<B>,
+ rope: &PrecalculatedRoPE<B>,
children_per_node: usize,
target_embedding: &Embedding<B>,
encoder: &mut Encoder<B>,
@@ -530,15 +552,6 @@ impl<B: Backend> Weaver<B> {
.token_embedding_projection
.encode(normalized_embedding, nodes.count, encoder)
.map_err(WeaverEncodeError::Backend)?;
- self.node_position_add.encode(
- None::<&Allocation<B>>,
- &self.position_embeddings,
- Some(nodes.metadata),
- &mut residual_input,
- self.model_dim as u32,
- (nodes.count * self.model_dim) as u32,
- encoder,
- );
let mut residual_state = encoder.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;
let node_capacity = node_cache.capacity;
@@ -551,6 +564,7 @@ impl<B: Backend> Weaver<B> {
&mut node_cache.layers[layer_index],
node_capacity,
nodes,
+ rope,
prefix_cache.length,
encoder,
)
@@ -623,13 +637,19 @@ impl<B: Backend> Weaver<B> {
impl<B: Backend> WeaverLayer<B> {
fn new(
context: &B::Context,
- model_dim: usize,
- hidden_dim: usize,
- num_heads: usize,
+ config: &WeaverConfig,
add_to_residual: bool,
- norm_config: &NormalizationConfig,
parameter_tree: &ParameterTree<B>,
) -> Result<Self, WeaverNewError<B>> {
+ let WeaverConfig {
+ model_dim,
+ hidden_dim,
+ num_heads,
+ max_depth,
+ ref norm_config,
+ ref linear_config,
+ ..
+ } = *config;
let head_dim = model_dim / num_heads;
let attention_scale = 1.0 / (head_dim as f32).sqrt();
let qkv_projection = <dyn Linear<B>>::new(
@@ -665,7 +685,7 @@ impl<B: Backend> WeaverLayer<B> {
)
.map_err(WeaverNewError::Backend)?;
let attention_prepare =
- <B::Kernels as Kernels>::AttentionPrepareKernel::new(context, DATA_TYPE, DataType::F32, true, false)
+ <B::Kernels as Kernels>::AttentionPrepareKernel::new(context, DATA_TYPE, ROPE_DATA_TYPE, true, true)
.map_err(WeaverNewError::Backend)?;
let pre_attention_norm = Normalization::new(
model_dim,
@@ -691,24 +711,15 @@ impl<B: Backend> WeaverLayer<B> {
&parameter_tree.subtree("pre_mlp_norm")?,
context,
)?;
- let up_projection = <dyn Linear<B>>::new(
+ let (mlp, up_input_hadamard_factors) = <dyn Mlp<B>>::new(
+ &weaver_mlp_config(linear_config.clone()),
model_dim,
- [hidden_dim],
- true,
- context,
- DATA_TYPE,
- &parameter_tree.subtree("up_projection")?,
- )?;
- let down_projection = <dyn Linear<B>>::new(
hidden_dim,
- [model_dim],
- true,
context,
+ &parameter_tree.subtree("mlp")?,
DATA_TYPE,
- &parameter_tree.subtree("down_projection")?,
)?;
- let activation = <B::Kernels as Kernels>::ActivationKernel::new(context, DATA_TYPE, true)
- .map_err(WeaverNewError::Backend)?;
+ assert!(up_input_hadamard_factors.is_none(), "Weaver MLP does not support input Hadamard factors");
let ancestor_attention =
<B::Kernels as Kernels>::AncestorAttentionKernel::new(context, head_dim as u32, num_heads as u32)
.map_err(WeaverNewError::Backend)?;
@@ -719,15 +730,13 @@ impl<B: Backend> WeaverLayer<B> {
attention_prepare,
pre_attention_norm,
pre_mlp_norm,
- up_projection,
- down_projection,
- activation,
+ mlp,
ancestor_attention,
attention_scale,
model_dim,
- hidden_dim,
num_heads,
head_dim,
+ max_depth,
})
}
@@ -735,13 +744,14 @@ impl<B: Backend> WeaverLayer<B> {
&self,
residual_input: Allocation<B>,
residual_state: &mut Allocation<B>,
+ rope: &PrecalculatedRoPE<B>,
token_count: usize,
encoder: &mut Encoder<B>,
) -> Result<PrefixLayerOutput<B>, B::Error> {
let PreparedPrefixAttention {
queries,
kv_cache,
- } = self.encode_prefix_attention(&residual_input, residual_state, token_count, encoder)?;
+ } = self.encode_prefix_attention(&residual_input, residual_state, rope, token_count, encoder)?;
let state_type = AttentionStateType::Full {
length: 0,
};
@@ -769,6 +779,7 @@ impl<B: Backend> WeaverLayer<B> {
&self,
residual_input: &Allocation<B>,
residual_state: &mut Allocation<B>,
+ rope: &PrecalculatedRoPE<B>,
token_count: usize,
encoder: &mut Encoder<B>,
) -> Result<PreparedPrefixAttention<B>, B::Error> {
@@ -785,12 +796,12 @@ impl<B: Backend> WeaverLayer<B> {
&mut queries,
Some(keys),
Some(values),
- None::<&Allocation<B>>,
- None::<&Allocation<B>>,
+ Some(&rope.cosines),
+ Some(&rope.sines),
self.num_heads as u32,
Some(self.num_heads as u32),
self.head_dim as u32,
- None,
+ Some(rope.dim as u32),
Some(0),
token_count as u32,
encoder,
@@ -809,6 +820,7 @@ impl<B: Backend> WeaverLayer<B> {
node_kv_cache: &mut Allocation<B>,
node_capacity: u32,
nodes: &NodeBatch<'_, B>,
+ rope: &PrecalculatedRoPE<B>,
prefix_length: usize,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
@@ -824,6 +836,9 @@ impl<B: Backend> WeaverLayer<B> {
prefix_kv,
node_kv_cache,
&current_qkv,
+ &rope.cosines,
+ &rope.sines,
+ nodes.metadata,
nodes.ancestor_indices,
ancestor_counts,
tree_slot_indices,
@@ -832,6 +847,7 @@ impl<B: Backend> WeaverLayer<B> {
prefix_length as u32,
nodes.ancestor_stride as u32,
node_capacity,
+ self.max_depth as u32,
self.attention_scale,
encoder,
);
@@ -848,15 +864,7 @@ impl<B: Backend> WeaverLayer<B> {
let projected_attention = self.out_projection.encode(attention_output, token_count, encoder)?;
let mlp_input =
self.pre_mlp_norm.encode(&projected_attention, 0, token_count, Some(residual_state), encoder)?;
- let mut mlp_hidden = self.up_projection.encode(mlp_input, token_count, encoder)?;
- self.activation.encode(
- None::<&Allocation<B>>,
- &mut mlp_hidden,
- (token_count * self.hidden_dim) as u32,
- crate::backends::common::gpu_types::ActivationType::GELUExact,
- encoder,
- );
- self.down_projection.encode(mlp_hidden, token_count, encoder)
+ self.mlp.encode(mlp_input, token_count, encoder)
}
}
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/ancestor_attention_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/ancestor_attention_test.rs
index d07a35363..3f8703407 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/ancestor_attention_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/ancestor_attention_test.rs
@@ -7,7 +7,9 @@ use proc_macros::uzu_test;
use crate::{
backends::{
- common::{Allocation, Backend, Encoder, Kernels, kernel::AncestorAttentionKernel},
+ common::{
+ Allocation, Backend, Encoder, Kernels, gpu_types::weaver::MetadataIdx, kernel::AncestorAttentionKernel,
+ },
cpu::Cpu,
metal::Metal,
},
@@ -19,6 +21,7 @@ use crate::{
const HEAD_DIM: usize = 128;
const NUM_HEADS: u32 = 16;
+const MAX_DEPTH: u32 = 8;
struct Runner<B: Backend> {
context: Arc<B::Context>,
@@ -26,6 +29,9 @@ struct Runner<B: Backend> {
prefix_kv: Allocation<B>,
node_kv: Allocation<B>,
current_qkv: Allocation<B>,
+ cosines: Allocation<B>,
+ sines: Allocation<B>,
+ node_metadata: Allocation<B>,
ancestor_indices: Allocation<B>,
ancestor_counts: Allocation<B>,
node_indices: Allocation<B>,
@@ -63,6 +69,24 @@ impl<B: Backend> Runner<B> {
}
}
+ let half_dim = HEAD_DIM / 2;
+ let mut cosines = vec![0.0f32; (MAX_DEPTH as usize + 1) * HEAD_DIM];
+ let mut sines = vec![0.0f32; (MAX_DEPTH as usize + 1) * HEAD_DIM];
+ for position in 0..=MAX_DEPTH as usize {
+ for pair in 0..half_dim {
+ let angle = position as f32 / 10_000f32.powf(2.0 * pair as f32 / HEAD_DIM as f32);
+ let row_base = position * HEAD_DIM;
+ cosines[row_base + pair] = angle.cos();
+ cosines[row_base + half_dim + pair] = angle.cos();
+ sines[row_base + pair] = angle.sin();
+ sines[row_base + half_dim + pair] = angle.sin();
+ }
+ }
+ let mut node_metadata = vec![0u32; rows * MetadataIdx::COUNT];
+ for row in 0..rows {
+ node_metadata[MetadataIdx::Depth as usize * rows + row] = (row as u32 * 3) % (MAX_DEPTH + 2);
+ }
+
let context = create_context::<B>();
let kernel =
<B::Kernels as Kernels>::AncestorAttentionKernel::new(context.as_ref(), HEAD_DIM as u32, NUM_HEADS)
@@ -71,6 +95,9 @@ impl<B: Backend> Runner<B> {
prefix_kv: alloc_allocation_with_data::<B, bf16>(&context, &values(prefix_length * kv_width, 0)),
node_kv: alloc_allocation_with_data::<B, bf16>(&context, &values(nodes * kv_width, 11)),
current_qkv: alloc_allocation_with_data::<B, bf16>(&context, &values(rows * qkv_width, 29)),
+ cosines: alloc_allocation_with_data::<B, f32>(&context, &cosines),
+ sines: alloc_allocation_with_data::<B, f32>(&context, &sines),
+ node_metadata: alloc_allocation_with_data::<B, u32>(&context, &node_metadata),
ancestor_indices: alloc_allocation_with_data::<B, u32>(&context, &ancestor_indices),
ancestor_counts: alloc_allocation_with_data::<B, u32>(&context, &ancestor_counts),
node_indices: alloc_allocation_with_data::<B, u32>(&context, &node_indices),
@@ -94,6 +121,9 @@ impl<B: Backend> Runner<B> {
&self.prefix_kv,
&mut self.node_kv,
&self.current_qkv,
+ &self.cosines,
+ &self.sines,
+ &self.node_metadata,
&self.ancestor_indices,
&self.ancestor_counts,
&self.node_indices,
@@ -102,6 +132,7 @@ impl<B: Backend> Runner<B> {
self.prefix_length,
self.ancestor_stride,
self.node_capacity,
+ MAX_DEPTH,
1.0 / (HEAD_DIM as f32).sqrt(),
&mut encoder,
);
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/tensor_add_bias_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/tensor_add_bias_test.rs
index 42e29b22e..fcbf24dd9 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/tensor_add_bias_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/tensor_add_bias_test.rs
@@ -6,7 +6,7 @@ use proc_macros::uzu_test;
use crate::{
array::ArrayElement,
- backends::common::{Allocation, Backend, Context, Encoder, Kernels, kernel::TensorAddBiasKernel},
+ backends::common::{Backend, Context, Encoder, Kernels, kernel::TensorAddBiasKernel},
tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},
};
@@ -63,7 +63,6 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
T::data_type(),
T::data_type(),
in_place,
- false,
)
.expect("Failed to create TensorAddBiasKernel");
@@ -79,7 +78,6 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
kernel.encode(
input_allocation.as_ref(),
&bias_allocation,
- None::<&Allocation<B>>,
&mut output_allocation,
input.num_cols,
input.length,
@@ -127,30 +125,3 @@ fn test_bf16() {
fn test_bf16_in_place() {
test::<bf16>(true);
}
-
-#[uzu_test]
-fn test_bf16_indexed_rows() {
- let values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0].map(bf16::from_f32);
- let bias = [10.0f32, 20.0, 30.0, 40.0, 50.0, 60.0];
- let bias_row_indices = [1u32, 0];
- let expected = [41.0, 52.0, 63.0, 14.0, 25.0, 36.0].map(bf16::from_f32);
-
- for_each_backend!(|B| {
- let context = <B as Backend>::Context::new().unwrap();
- let kernel = <<B as Backend>::Kernels as Kernels>::TensorAddBiasKernel::new(
- &context,
- bf16::data_type(),
- f32::data_type(),
- true,
- true,
- )
- .unwrap();
- let mut output = alloc_allocation_with_data::<B, bf16>(&context, &values);
- let bias = alloc_allocation_with_data::<B, f32>(&context, &bias);
- let bias_row_indices = alloc_allocation_with_data::<B, u32>(&context, &bias_row_indices);
- let mut encoder = Encoder::new(context.as_ref()).unwrap();
- kernel.encode(None::<&Allocation<B>>, &bias, Some(&bias_row_indices), &mut output, 3, 6, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- assert_eq!(allocation_to_vec::<B, bf16>(&output), expected);
- });
-}