Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Fix `support_mxu` leak and refactor `AttentinonGemm` dispatch (#587)

CCYehb670039f4f92
diff --git a/crates/backend-uzu/src/backends/common/context.rs b/crates/backend-uzu/src/backends/common/context.rs
index 6c2df93a2..bb8fbd67a 100644
--- a/crates/backend-uzu/src/backends/common/context.rs
+++ b/crates/backend-uzu/src/backends/common/context.rs
@@ -44,8 +44,4 @@ pub trait Context: Sized {
fn stop_capture(&self) -> Result<(), <Self::Backend as Backend>::Error>;
fn sparse_buffers_supported(&self) -> bool;
-
- fn supports_mxu(&self) -> bool {
- false
- }
}
diff --git a/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs
new file mode 100644
index 000000000..e30499d1e
--- /dev/null
+++ b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs
@@ -0,0 +1,48 @@
+use std::convert::Infallible;
+
+use crate::{
+ backends::common::{Allocation, Backend, BufferArg, Encoder, kernel::Kernels},
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+pub trait AttentionGemmCore<B: Backend<Kernels: Kernels<AttentionGemmCore = Self>>>: Sized {
+ fn is_supported(
+ arguments: &AttentionCoreNewArguments,
+ context: &B::Context,
+ ) -> Result<bool, B::Error>;
+
+ fn new(
+ context: &B::Context,
+ arguments: &AttentionCoreNewArguments,
+ ) -> Result<Self, B::Error>;
+
+ fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error>;
+}
+
+impl<B: Backend<Kernels: Kernels<AttentionGemmCore = Infallible>>> AttentionGemmCore<B> for Infallible {
+ fn is_supported(
+ _arguments: &AttentionCoreNewArguments,
+ _context: &B::Context,
+ ) -> Result<bool, B::Error> {
+ Ok(false)
+ }
+
+ fn new(
+ _context: &B::Context,
+ _arguments: &AttentionCoreNewArguments,
+ ) -> Result<Self, B::Error> {
+ unreachable!("unsupported attention core should not be constructed")
+ }
+
+ fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ _arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ _encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ match *self {}
+ }
+}
diff --git a/crates/backend-uzu/src/backends/common/kernel/attention_gemm/mod.rs b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/mod.rs
new file mode 100644
index 000000000..608e559cc
--- /dev/null
+++ b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/mod.rs
@@ -0,0 +1,3 @@
+mod kernel;
+
+pub use kernel::AttentionGemmCore;
diff --git a/crates/backend-uzu/src/backends/common/kernel/mod.rs b/crates/backend-uzu/src/backends/common/kernel/mod.rs
index 0bd082fc3..c022189a3 100644
--- a/crates/backend-uzu/src/backends/common/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/mod.rs
@@ -1,5 +1,6 @@
use crate::backends::common::Backend;
+pub mod attention_gemm;
pub mod matmul;
include!(concat!(env!("OUT_DIR"), "/traits.rs"));
@@ -8,6 +9,7 @@ pub trait Kernels: Sized {
type Backend: Backend<Kernels = Self>;
autogen_kernels!();
+ type AttentionGemmCore: attention_gemm::AttentionGemmCore<Self::Backend>;
type MatmulKernel: matmul::MatmulKernel<Backend = Self::Backend>;
}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_gemm.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_gemm.rs
deleted file mode 100644
index ccdecba2f..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_gemm.rs
+++ /dev/null
@@ -1,132 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::{
- array::ArrayElement,
- backends::{common::gpu_types::trie::TrieNode, cpu::kernel::attention::mask::should_use_key},
-};
-
-#[kernel(AttentionGemm)]
-#[variants(T, f32, f16, bf16)]
-#[variants(BK, 16, 32)]
-#[variants(BD, 64, 128, 256)]
-#[variants(USE_MXU, false)]
-pub fn attention_gemm<T: ArrayElement + Float, const BK: u32, const BD: u32, const USE_MXU: bool>(
- q: *const T,
- k: *const T,
- v: *const T,
- o: *mut T,
- params: crate::backends::common::gpu_types::attention::AttnParams,
- #[optional(is_kv_cache_ring)] ring_params: Option<crate::backends::common::gpu_types::ring::RingParams>,
- #[optional(is_trie)] trie: Option<*const TrieNode>,
- #[optional(is_sliding_window)] sliding_window_size: Option<u32>,
- #[optional(has_sinks)] sinks: Option<*const T>,
- num_heads: u32,
- suffix_length: u32,
- #[specialize] align_q: bool,
- #[specialize] align_k: bool,
- #[specialize] is_kv_cache_ring: bool,
- #[specialize] is_causal: bool,
- #[specialize] is_trie: bool,
- #[specialize] is_sliding_window: bool,
- #[specialize] has_sinks: bool,
-) {
- assert_eq!(suffix_length, params.q_len);
- assert_eq!(align_q, params.q_rem == 0);
- assert_eq!(align_k, params.k_rem == 0);
- assert_eq!(sliding_window_size.is_some(), is_sliding_window);
-
- let q_len = params.q_len as usize;
- let k_len = params.k_len as usize;
- let head_dim = BD as usize;
- let prefix_length = params.q_off as usize;
- let suffix_position = if is_kv_cache_ring {
- ring_params.unwrap().ring_length as usize
- } else {
- prefix_length
- };
-
- for head_idx in 0..num_heads as usize {
- let kv_head_idx = head_idx / params.gqa_factor as usize;
-
- let q_head = unsafe { q.add(head_idx * params.q_strides[1] as usize) };
- let k_head = unsafe { k.add(kv_head_idx * params.k_strides[1] as usize) };
- let v_head = unsafe { v.add(kv_head_idx * params.v_strides[1] as usize) };
- let o_head = unsafe { o.add(head_idx * params.o_strides[1] as usize) };
-
- for qi in 0..q_len {
- let q_row = unsafe { q_head.add(qi * params.q_strides[2] as usize) };
- let o_row = unsafe { o_head.add(qi * params.o_strides[2] as usize) };
-
- let query_position = if is_trie {
- let trie_node = unsafe { &*trie.unwrap().add(qi) };
- suffix_position + trie_node.height as usize
- } else {
- suffix_position + qi
- };
-
- // Read query row and pre-scale
- let mut q_vec = vec![0.0f32; head_dim];
- for j in 0..head_dim {
- q_vec[j] = params.scale * unsafe { *q_row.add(j) }.to_f32().unwrap();
- }
-
- let mut max_score = f32::NEG_INFINITY;
- let mut sum_exp = 0.0f32;
- let mut o_acc = vec![0.0f32; head_dim];
-
- // Initialize with attention sinks if present
- if has_sinks {
- max_score = unsafe { *sinks.unwrap().add(head_idx) }.to_f32().unwrap();
- sum_exp = 1.0;
- }
-
- // Loop over all key positions
- for ki in 0..k_len {
- if !should_use_key(
- ring_params,
- trie,
- sliding_window_size,
- qi as u32,
- prefix_length as u32,
- suffix_position as u32,
- query_position as u32,
- ki as u32,
- is_causal,
- ) {
- continue;
- }
-
- // Compute dot product: score = q . k[ki]
- let k_row = unsafe { k_head.add(ki * params.k_strides[2] as usize) };
- let mut score = 0.0f32;
- for j in 0..head_dim {
- score += q_vec[j] * unsafe { *k_row.add(j) }.to_f32().unwrap();
- }
-
- // Online softmax update
- let new_max = f32::max(max_score, score);
- let factor = (max_score - new_max).exp();
- let exp_score = (score - new_max).exp();
-
- max_score = new_max;
- sum_exp = sum_exp * factor + exp_score;
-
- // Update output accumulator
- let v_row = unsafe { v_head.add(ki * params.v_strides[2] as usize) };
- for j in 0..head_dim {
- o_acc[j] = o_acc[j] * factor + exp_score * unsafe { *v_row.add(j) }.to_f32().unwrap();
- }
- }
-
- // Normalize and write output
- let inv_sum = 1.0 / sum_exp;
- for j in 0..head_dim {
- unsafe {
- *o_row.add(j) = T::from(o_acc[j] * inv_sum).unwrap();
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
index c4798489a..c60c4c8e1 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
@@ -1,5 +1,4 @@
pub mod attention_fallback;
-pub mod attention_gemm;
pub mod attention_prepare;
pub mod attention_single_pass;
pub mod attention_two_pass;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
index f2ee15930..f0095bf5a 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
@@ -1,3 +1,5 @@
+use std::convert::Infallible;
+
use crate::backends::{common::Kernels, cpu::Cpu};
mod activation;
@@ -30,5 +32,6 @@ impl Kernels for CpuKernels {
type Backend = Cpu;
autogen_kernels!();
+ type AttentionGemmCore = Infallible;
type MatmulKernel = matmul::MatmulCpuKernel;
}
diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rs
index e2c583fc1..d25889b77 100644
--- a/crates/backend-uzu/src/backends/metal/context.rs
+++ b/crates/backend-uzu/src/backends/metal/context.rs
@@ -241,8 +241,4 @@ impl Context for MetalContext {
fn sparse_buffers_supported(&self) -> bool {
self.device.supports_placement_sparse_resources()
}
-
- fn supports_mxu(&self) -> bool {
- self.supports_mxu()
- }
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention.rs b/crates/backend-uzu/src/backends/metal/kernel/attention.rs
new file mode 100644
index 000000000..46a1864ea
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention.rs
@@ -0,0 +1,182 @@
+use std::{
+ cell::{RefCell, RefMut},
+ collections::{HashMap, hash_map::Entry},
+};
+
+use crate::{
+ array::size_for_shape,
+ backends::{
+ common::{Allocation, BufferArg, Encoder, gpu_types::AttnParams, kernel::attention_gemm::AttentionGemmCore},
+ metal::{Metal, context::MetalContext, error::MetalError, kernel::AttentionGemmMetalKernel},
+ },
+ data_type::DataType,
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+pub struct AttentionGemmMetalCore {
+ kernels: RefCell<HashMap<AttentionGemmKey, AttentionGemmMetalKernel>>,
+ head_dim: usize,
+ num_groups: usize,
+ num_q_heads: usize,
+ sliding_window_size: Option<usize>,
+ scale: Option<f32>,
+ data_type: DataType,
+ simd_bk: u32,
+ is_kv_cache_ring: bool,
+ is_causal: bool,
+ is_trie: bool,
+ is_sliding_window: bool,
+ has_sinks: bool,
+}
+
+#[derive(Clone, Copy, Hash, PartialEq, Eq)]
+struct AttentionGemmKey {
+ use_mxu: bool,
+ align_q: bool,
+ align_k: bool,
+}
+
+fn retile_params(
+ mut params: AttnParams,
+ bq: u32,
+ bk: u32,
+) -> AttnParams {
+ params.nq_aligned = params.q_len / bq;
+ params.q_rem = params.q_len % bq;
+ params.nk = params.k_len.div_ceil(bk);
+ params.nk_aligned = params.k_len / bk;
+ params.k_rem = params.k_len % bk;
+ params
+}
+
+impl AttentionGemmMetalCore {
+ fn get_or_create(
+ &self,
+ context: &MetalContext,
+ key: AttentionGemmKey,
+ ) -> Result<RefMut<'_, AttentionGemmMetalKernel>, MetalError> {
+ let mut kernels = self.kernels.borrow_mut();
+ if let Entry::Vacant(entry) = kernels.entry(key) {
+ let bk = if key.use_mxu {
+ 32
+ } else {
+ self.simd_bk
+ };
+ let kernel = AttentionGemmMetalKernel::new(
+ context,
+ self.data_type,
+ bk,
+ self.head_dim as u32,
+ key.use_mxu,
+ key.align_q,
+ key.align_k,
+ self.is_kv_cache_ring,
+ self.is_causal,
+ self.is_trie,
+ self.is_sliding_window,
+ self.has_sinks,
+ )?;
+ entry.insert(kernel);
+ }
+ Ok(RefMut::map(kernels, |kernels| kernels.get_mut(&key).expect("kernel was just initialized")))
+ }
+}
+
+impl AttentionGemmCore<Metal> for AttentionGemmMetalCore {
+ fn is_supported(
+ arguments: &AttentionCoreNewArguments,
+ _context: &MetalContext,
+ ) -> Result<bool, MetalError> {
+ Ok(matches!(arguments.head_dim, 64 | 128 | 256))
+ }
+
+ fn new(
+ _context: &MetalContext,
+ arguments: &AttentionCoreNewArguments,
+ ) -> Result<Self, MetalError> {
+ let simd_bk = if arguments.head_dim < 128 {
+ 32
+ } else {
+ 16
+ };
+
+ Ok(Self {
+ kernels: RefCell::new(HashMap::new()),
+ head_dim: arguments.head_dim,
+ num_groups: arguments.num_groups,
+ num_q_heads: arguments.num_q_heads,
+ sliding_window_size: arguments.sliding_window_size,
+ scale: arguments.scale,
+ data_type: arguments.data_type,
+ simd_bk,
+ is_kv_cache_ring: arguments.is_kv_cache_ring,
+ is_causal: arguments.is_causal,
+ is_trie: arguments.is_trie,
+ is_sliding_window: arguments.sliding_window_size.is_some(),
+ has_sinks: arguments.has_sinks,
+ })
+ }
+
+ fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, Metal, KT, VT>,
+ encoder: &mut Encoder<Metal>,
+ ) -> Result<Allocation<Metal>, MetalError> {
+ let mut output = encoder.allocate_constant(size_for_shape(
+ &[arguments.suffix_length, self.num_q_heads, self.head_dim],
+ self.data_type,
+ ))?;
+
+ let use_mxu = arguments.suffix_length >= 64
+ && encoder.context().supports_mxu()
+ && matches!(self.data_type, DataType::BF16 | DataType::F16)
+ && matches!(self.head_dim, 64 | 128);
+ let (bq, bk) = if use_mxu {
+ (64, 32)
+ } else {
+ (32, self.simd_bk)
+ };
+ let params = retile_params(
+ AttnParams {
+ q_strides: [0, (arguments.suffix_length * self.head_dim) as u64, self.head_dim as u64],
+ k_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
+ v_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
+ o_strides: [0, self.head_dim as u64, (self.num_q_heads * self.head_dim) as u64],
+ gqa_factor: (self.num_q_heads / self.num_groups) as u32,
+ scale: self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt()),
+ q_len: arguments.suffix_length as u32,
+ k_len: (arguments.state_type.physical_prefix_length() + arguments.suffix_length) as u32,
+ q_off: arguments.state_type.physical_prefix_length() as u32,
+ nq_aligned: 0,
+ q_rem: 0,
+ nk: 0,
+ nk_aligned: 0,
+ k_rem: 0,
+ },
+ bq,
+ bk,
+ );
+ let key = AttentionGemmKey {
+ use_mxu,
+ align_q: params.q_rem == 0,
+ align_k: params.k_rem == 0,
+ };
+ let kernel = self.get_or_create(encoder.context(), key)?;
+
+ kernel.encode(
+ arguments.queries,
+ arguments.keys,
+ arguments.values,
+ &mut output,
+ params,
+ arguments.state_type.ring_params(),
+ arguments.trie,
+ self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
+ arguments.sinks,
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ encoder,
+ );
+ Ok(output)
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_gemm.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_gemm.metal
index 7a2e7afc0..d9d2bd890 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_gemm.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_gemm.metal
@@ -44,7 +44,7 @@ VARIANTS(USE_MXU, false, true)
CONSTRAINT(!USE_MXU || BK == 32)
CONSTRAINT(!USE_MXU || T != "float")
CONSTRAINT(!USE_MXU || BD != 256)
-PUBLIC KERNEL(AttentionGemm)(
+KERNEL(AttentionGemm)(
const device T* q,
const device T* k,
const device T* v,
diff --git a/crates/backend-uzu/src/backends/metal/kernel/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
index 1ea726cc4..02c955e65 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
@@ -6,6 +6,7 @@ use crate::backends::{
metal::Metal,
};
+pub mod attention;
#[path = "gdn_tree_verify/build_tree_out_dispatch_helper.rs"]
mod build_tree_out_dispatch_helper;
pub mod matmul;
@@ -22,5 +23,6 @@ impl Kernels for MetalKernels {
type Backend = Metal;
autogen_kernels!();
+ type AttentionGemmCore = attention::AttentionGemmMetalCore;
type MatmulKernel = matmul::MatmulMetalKernel;
}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs
deleted file mode 100644
index 6646415ca..000000000
--- a/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs
+++ /dev/null
@@ -1,140 +0,0 @@
-use std::mem::MaybeUninit;
-
-use bitflags::bitflags;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, BufferArg, Encoder, Kernels, gpu_types::AttnParams, kernel::AttentionGemmKernel,
- },
- data_type::DataType,
- encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
-};
-
-bitflags! {
- pub struct AttentionGemmKey: usize {
- const ALIGNED_Q = 1 << 0;
- const ALIGNED_KV = 1 << 1;
- }
-}
-
-const ATTENTION_GEMM_KEYS: usize = AttentionGemmKey::all().bits() + 1;
-
-pub struct AttentionGemmCore<B: Backend> {
- head_dim: usize,
- num_groups: usize,
- num_q_heads: usize,
- bk: usize,
- bq: usize,
- sliding_window_size: Option<usize>,
- scale: Option<f32>,
- data_type: DataType,
- kernels: [<B::Kernels as Kernels>::AttentionGemmKernel; ATTENTION_GEMM_KEYS],
-}
-
-impl<B: Backend> AttentionGemmCore<B> {
- pub fn new(
- arguments: &AttentionCoreNewArguments,
- use_mxu: bool,
- context: &B::Context,
- ) -> Result<Self, B::Error> {
- let bk = if arguments.head_dim < 128 || use_mxu {
- 32
- } else {
- 16
- };
- let bq = if use_mxu {
- 64
- } else {
- 32
- };
-
- let mut kernels = [const { MaybeUninit::uninit() }; ATTENTION_GEMM_KEYS];
- for (index, kernel) in kernels.iter_mut().enumerate() {
- let key = AttentionGemmKey::from_bits(index).unwrap();
-
- kernel.write(<B::Kernels as Kernels>::AttentionGemmKernel::new(
- context,
- arguments.data_type,
- bk as u32,
- arguments.head_dim as u32,
- use_mxu,
- key.contains(AttentionGemmKey::ALIGNED_Q),
- key.contains(AttentionGemmKey::ALIGNED_KV),
- arguments.is_kv_cache_ring,
- arguments.is_causal,
- arguments.is_trie,
- arguments.sliding_window_size.is_some(),
- arguments.has_sinks,
- )?);
- }
-
- Ok(Self {
- head_dim: arguments.head_dim,
- num_groups: arguments.num_groups,
- num_q_heads: arguments.num_q_heads,
- bk,
- bq,
- sliding_window_size: arguments.sliding_window_size,
- scale: arguments.scale,
- data_type: arguments.data_type,
- kernels: kernels.map(|kernel| unsafe { kernel.assume_init() }),
- })
- }
-
- pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
- &self,
- arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let mut key = AttentionGemmKey::empty();
-
- if arguments.suffix_length.is_multiple_of(self.bq) {
- key.insert(AttentionGemmKey::ALIGNED_Q);
- }
- if (arguments.state_type.physical_prefix_length() + arguments.suffix_length).is_multiple_of(self.bk) {
- key.insert(AttentionGemmKey::ALIGNED_KV);
- }
-
- let mut output = encoder.allocate_constant(size_for_shape(
- &[arguments.suffix_length, self.num_q_heads, self.head_dim],
- self.data_type,
- ))?;
- self.kernels[key.bits()].encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
- &mut output,
- AttnParams {
- q_strides: [0, (arguments.suffix_length * self.head_dim) as u64, self.head_dim as u64],
- k_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
- v_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
- o_strides: [0, self.head_dim as u64, (self.num_q_heads * self.head_dim) as u64],
- gqa_factor: (self.num_q_heads / self.num_groups) as u32,
- scale: self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt()),
- q_len: arguments.suffix_length as u32,
- k_len: (arguments.state_type.physical_prefix_length() + arguments.suffix_length) as u32,
- q_off: arguments.state_type.physical_prefix_length() as u32,
- nq_aligned: (arguments.suffix_length / self.bq) as u32,
- q_rem: (arguments.suffix_length % self.bq) as u32,
- nk: (arguments.state_type.physical_prefix_length() + arguments.suffix_length).div_ceil(self.bk) as u32,
- nk_aligned: ((arguments.state_type.physical_prefix_length() + arguments.suffix_length) / self.bk)
- as u32,
- k_rem: ((arguments.state_type.physical_prefix_length() + arguments.suffix_length) % self.bk) as u32,
- },
- arguments.state_type.ring_params(),
- arguments.trie,
- self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
- arguments.sinks,
- self.num_q_heads as u32,
- arguments.suffix_length as u32,
- encoder,
- );
-
- Ok(output)
- }
-}
-
-#[cfg(test)]
-#[path = "../../../../../unit/encodable_block/attention_gemm_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs
index 4e4c8db8a..0280914df 100644
--- a/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs
@@ -1,17 +1,16 @@
use crate::{
- backends::common::{Allocation, Backend, BufferArg, Context, Encoder},
+ backends::common::{
+ Allocation, Backend, BufferArg, Encoder, Kernels,
+ kernel::attention_gemm::AttentionGemmCore as AttentionGemmCoreTrait,
+ },
data_type::DataType,
encodable_block::mixer::attention::{
- core::{
- fallback::AttentionFallbackCore, gemm::AttentionGemmCore, single_pass::AttentionSinglePassCore,
- two_pass::AttentionTwoPassCore,
- },
+ core::{fallback::AttentionFallbackCore, single_pass::AttentionSinglePassCore, two_pass::AttentionTwoPassCore},
state::AttentionStateType,
},
};
mod fallback;
-mod gemm;
mod single_pass;
mod two_pass;
@@ -39,8 +38,7 @@ pub struct AttentionCoreEncodeArguments<'a, B: Backend, KT: BufferArg<'a, B>, VT
}
pub struct AttentionCores<B: Backend> {
- gemm_mxu: Option<AttentionGemmCore<B>>,
- gemm_simd: Option<AttentionGemmCore<B>>,
+ gemm: Option<<B::Kernels as Kernels>::AttentionGemmCore>,
fallback: Option<AttentionFallbackCore<B>>,
two_pass: AttentionTwoPassCore<B>,
single_pass: AttentionSinglePassCore<B>,
@@ -51,16 +49,10 @@ impl<B: Backend> AttentionCores<B> {
arguments: AttentionCoreNewArguments,
context: &B::Context,
) -> Result<Self, B::Error> {
- let gemm_mxu = if matches!(arguments.head_dim, 64 | 128)
- && matches!(arguments.data_type, DataType::BF16 | DataType::F16)
- && context.supports_mxu()
- {
- Some(AttentionGemmCore::new(&arguments, true, context)?)
- } else {
- None
- };
- let gemm_simd = if matches!(arguments.head_dim, 64 | 128 | 256) {
- Some(AttentionGemmCore::new(&arguments, false, context)?)
+ let gemm = if <<B::Kernels as Kernels>::AttentionGemmCore as AttentionGemmCoreTrait<B>>::is_supported(
+ &arguments, context,
+ )? {
+ Some(<<B::Kernels as Kernels>::AttentionGemmCore as AttentionGemmCoreTrait<B>>::new(context, &arguments)?)
} else {
None
};
@@ -73,8 +65,7 @@ impl<B: Backend> AttentionCores<B> {
let single_pass = AttentionSinglePassCore::new(&arguments, context)?;
Ok(Self {
- gemm_mxu,
- gemm_simd,
+ gemm,
fallback,
two_pass,
single_pass,
@@ -85,14 +76,10 @@ impl<B: Backend> AttentionCores<B> {
arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, <B as Backend>::Error> {
- if arguments.suffix_length >= 64
- && let Some(gemm_mxu) = &self.gemm_mxu
+ if arguments.suffix_length > 8
+ && let Some(gemm) = &self.gemm
{
- gemm_mxu.encode(arguments, encoder)
- } else if arguments.suffix_length > 8
- && let Some(gemm_simd) = &self.gemm_simd
- {
- gemm_simd.encode(arguments, encoder)
+ gemm.encode(arguments, encoder)
} else if arguments.suffix_length > 8
&& let Some(fallback) = &self.fallback
{
@@ -108,3 +95,7 @@ impl<B: Backend> AttentionCores<B> {
#[cfg(test)]
#[path = "../../../../../unit/encodable_block/attention_test.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "../../../../../unit/encodable_block/attention_gemm_test.rs"]
+mod gemm_tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs
index 6413c514e..d54edcc74 100644
--- a/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs
@@ -25,7 +25,7 @@ use crate::{
utils::maybe_mut::MaybeMut,
};
-mod core;
+pub(crate) mod core;
mod mode;
mod qkv_norm;
mod state;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/matmul/dispatch_paths_test.rs b/crates/backend-uzu/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
index 19f38b4a7..042759c32 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
@@ -179,12 +179,9 @@ fn gemv_fp_output_transforms_bf16() {
}
#[uzu_test]
-fn small_m_mxu_tiles_parity() {
+fn small_m_tiles_parity() {
use crate::tests::matmul::Shape;
let context = MetalContext::new().expect("Metal context");
- if !context.supports_mxu() {
- return;
- }
let mut bf16_kernel = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
&context,
bf16::data_type(),
@@ -200,8 +197,10 @@ fn small_m_mxu_tiles_parity() {
)
.expect("MatmulKernel");
- for shape in [Shape::new(8, 256, 256), Shape::new(8, 512, 256)] {
- check_case::<bf16>(&context, &mut bf16_kernel, Some(GemmDispatchPath::Mxu), Case::new(shape), 1.0);
- check_case::<f32>(&context, &mut f32_kernel, Some(GemmDispatchPath::Mxu), Case::new(shape), 0.01);
+ for path in gemm_paths_for_hw(&context) {
+ for shape in [Shape::new(8, 256, 256), Shape::new(8, 512, 256)] {
+ check_case::<bf16>(&context, &mut bf16_kernel, Some(path), Case::new(shape), 1.0);
+ check_case::<f32>(&context, &mut f32_kernel, Some(path), Case::new(shape), 0.01);
+ }
}
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/out_test.rs b/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
index d459c6684..4a13e9b48 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
@@ -1,3 +1,5 @@
+#![cfg(metal_backend)]
+
use half::bf16;
use num_traits::Float;
use proc_macros::uzu_test;
@@ -8,6 +10,7 @@ use crate::{
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeOutKernel},
cpu::Cpu,
+ metal::Metal,
},
tests::{
assert::assert_eq_float,
@@ -124,12 +127,8 @@ fn check_shape<T: ArrayElement + Float + std::fmt::Display>(
for use_h0 in [false, true] {
let expected = run_build_tree_out::<Cpu, T>(shape, &inputs, use_h0, false, false);
for_each_non_cpu_backend!(|B| {
- let context = <B as Backend>::Context::new().expect("Failed to create Context");
for &(path, use_mxu, transposed_h0) in BUILD_TREE_OUT_PATHS {
- if use_mxu && !context.supports_mxu() {
- continue;
- }
- if transposed_h0 && !use_h0 {
+ if use_mxu || transposed_h0 && !use_h0 {
continue;
}
let actual = run_build_tree_out::<B, T>(shape, &inputs, use_h0, use_mxu, transposed_h0);
@@ -146,12 +145,32 @@ fn check_shape<T: ArrayElement + Float + std::fmt::Display>(
assert_eq_float::<T>(&expected, &actual, eps, &msg);
}
});
+
+ if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu() {
+ for &(path, use_mxu, transposed_h0) in BUILD_TREE_OUT_PATHS {
+ if !use_mxu || transposed_h0 && !use_h0 {
+ continue;
+ }
+ let actual = run_build_tree_out::<Metal, T>(shape, &inputs, use_h0, use_mxu, transposed_h0);
+ let msg = format!(
+ "backend {} path {path} use_h0 {use_h0} B{}_T{}_QK{}_HV{}_K{}_V{}",
+ std::any::type_name::<Metal>(),
+ shape.batch_size,
+ shape.tree_size,
+ shape.qk_heads,
+ shape.value_heads,
+ shape.head_k_dim,
+ shape.head_v_dim
+ );
+ assert_eq_float::<T>(&expected, &actual, eps, &msg);
+ }
+ }
}
}
#[uzu_test]
-fn test_build_tree_out_small() {
- let shape = Shape {
+fn test_build_tree_out_paths() {
+ let small = Shape {
batch_size: 2,
tree_size: 17,
qk_heads: 2,
@@ -159,13 +178,7 @@ fn test_build_tree_out_small() {
head_k_dim: 32,
head_v_dim: 32,
};
- check_shape::<bf16>(shape, 0.08);
- check_shape::<f32>(shape, 5e-3);
-}
-
-#[uzu_test]
-fn test_build_tree_out_gdn_shape() {
- let shape = Shape {
+ let gdn = Shape {
batch_size: 1,
tree_size: 49,
qk_heads: 16,
@@ -173,6 +186,8 @@ fn test_build_tree_out_gdn_shape() {
head_k_dim: 128,
head_v_dim: 128,
};
- check_shape::<bf16>(shape, 0.08);
- check_shape::<f32>(shape, 5e-3);
+ for shape in [small, gdn] {
+ check_shape::<bf16>(shape, 0.08);
+ check_shape::<f32>(shape, 5e-3);
+ }
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
index f492b49c2..627066065 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
@@ -1,3 +1,5 @@
+#![cfg(metal_backend)]
+
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
@@ -5,6 +7,7 @@ use crate::{
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeGramKernel},
cpu::Cpu,
+ metal::Metal,
},
data_type::DataType,
tests::{
@@ -20,6 +23,34 @@ const HEAD_K_DIM: usize = 128;
// 80 = two full 32-wide kh0 dv chunks plus a ragged 16-wide one.
const HEAD_V_DIM: usize = 80;
+struct Inputs {
+ trie: Vec<u32>,
+ q: Vec<f32>,
+ k: Vec<f32>,
+ prefix: Vec<f32>,
+ beta: Vec<f32>,
+ h0: Vec<f32>,
+ h0_idx: Vec<i32>,
+}
+
+fn make_inputs(tree_size: usize) -> Inputs {
+ let q_len = BATCH_SIZE * tree_size * K_HEADS * HEAD_K_DIM;
+ let scalar_len = BATCH_SIZE * tree_size * VALUE_HEADS;
+ let h0_len = BATCH_SIZE * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;
+ Inputs {
+ trie: build_trie(tree_size),
+ q: (0..q_len).map(|i| ((i as f32 * 0.017).sin() * 0.2) + 0.01).collect(),
+ k: (0..q_len).map(|i| ((i as f32 * 0.019).cos() * 0.18) - 0.02).collect(),
+ prefix: (0..scalar_len)
+ .map(|i| -((i % tree_size) as f32) * 0.01 - ((i % VALUE_HEADS) as f32) * 0.003)
+ .collect(),
+ beta: (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect(),
+ h0: (0..h0_len).map(|i| ((i as f32 * 0.007).sin() * 0.05) - 0.01).collect(),
+ // Batch 1 has no initial state: covers the kh0-skip path.
+ h0_idx: vec![0, -1],
+ }
+}
+
fn get_output<B: Backend>(
q: &[f32],
k: &[f32],
@@ -102,46 +133,28 @@ fn test_build_tree_gram_matches_cpu() {
let scale = (HEAD_K_DIM as f32).sqrt().recip();
for tree_size in [17, 64, 128] {
- let q_len = BATCH_SIZE * tree_size * K_HEADS * HEAD_K_DIM;
- let scalar_len = BATCH_SIZE * tree_size * VALUE_HEADS;
- let trie = build_trie(tree_size);
- let q = (0..q_len).map(|i| ((i as f32 * 0.017).sin() * 0.2) + 0.01).collect::<Vec<_>>();
- let k = (0..q_len).map(|i| ((i as f32 * 0.019).cos() * 0.18) - 0.02).collect::<Vec<_>>();
- let prefix = (0..scalar_len)
- .map(|i| -((i % tree_size) as f32) * 0.01 - ((i % VALUE_HEADS) as f32) * 0.003)
- .collect::<Vec<_>>();
- let beta = (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
- let h0_len = BATCH_SIZE * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;
- let h0 = (0..h0_len).map(|i| ((i as f32 * 0.007).sin() * 0.05) - 0.01).collect::<Vec<_>>();
- // Batch 1 has no initial state: covers the kh0-skip path.
- let h0_idx: Vec<i32> = vec![0, -1];
-
- let expected = get_output::<Cpu>(&q, &k, &trie, &prefix, &beta, &h0, &h0_idx, tree_size, scale, false);
+ let i = make_inputs(tree_size);
+ let expected =
+ get_output::<Cpu>(&i.q, &i.k, &i.trie, &i.prefix, &i.beta, &i.h0, &i.h0_idx, tree_size, scale, false);
for_each_non_cpu_backend!(|B| {
- let context = <<B as Backend>::Context as Context>::new().expect("Failed to create Context");
- let paths: &[bool] = if context.supports_mxu() {
- &[false, true]
- } else {
- &[false]
- };
-
- for &use_mxu in paths {
- let actual = get_output::<B>(&q, &k, &trie, &prefix, &beta, &h0, &h0_idx, tree_size, scale, use_mxu);
- let path = if use_mxu {
- "mxu"
- } else {
- "simdgroup"
- };
- let msg = format!("backend {} {path} tree_size {tree_size}", std::any::type_name::<B>());
- assert_eq_float::<f32>(&expected.0, &actual.0, 5e-3, &format!("a_packed {msg}"));
- assert_eq_float::<f32>(&expected.1, &actual.1, 5e-3, &format!("qkd {msg}"));
-
- // Ainv is compact [B * HV, ceil(T/16), 16, 16]; both CPU and GPU
- // pad ragged blocks with identity, so compare the whole buffer.
- assert_eq_float::<f32>(&expected.2, &actual.2, 1e-2, &format!("a_inv {msg}"));
- assert_eq_float::<f32>(&expected.3, &actual.3, 5e-3, &format!("kh0 {msg}"));
- }
+ let actual =
+ get_output::<B>(&i.q, &i.k, &i.trie, &i.prefix, &i.beta, &i.h0, &i.h0_idx, tree_size, scale, false);
+ let msg = format!("backend {} simdgroup tree_size {tree_size}", std::any::type_name::<B>());
+ assert_eq_float::<f32>(&expected.0, &actual.0, 5e-3, &format!("a_packed {msg}"));
+ assert_eq_float::<f32>(&expected.1, &actual.1, 5e-3, &format!("qkd {msg}"));
+ assert_eq_float::<f32>(&expected.2, &actual.2, 1e-2, &format!("a_inv {msg}"));
+ assert_eq_float::<f32>(&expected.3, &actual.3, 5e-3, &format!("kh0 {msg}"));
});
+
+ if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu() {
+ let actual =
+ get_output::<Metal>(&i.q, &i.k, &i.trie, &i.prefix, &i.beta, &i.h0, &i.h0_idx, tree_size, scale, true);
+ let msg = format!("backend {} path MXU tree_size {tree_size}", std::any::type_name::<Metal>());
+ assert_eq_float::<f32>(&expected.0, &actual.0, 5e-3, &format!("a_packed {msg}"));
+ assert_eq_float::<f32>(&expected.1, &actual.1, 5e-3, &format!("qkd {msg}"));
+ assert_eq_float::<f32>(&expected.2, &actual.2, 1e-2, &format!("a_inv {msg}"));
+ assert_eq_float::<f32>(&expected.3, &actual.3, 5e-3, &format!("kh0 {msg}"));
+ }
}
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs
index 781ebd6f8..45e94396b 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs
@@ -1,3 +1,5 @@
+#![cfg(metal_backend)]
+
use half::bf16;
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
@@ -7,6 +9,7 @@ use crate::{
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::TreeUpdateSolveKernel},
cpu::Cpu,
+ metal::Metal,
},
data_type::DataType,
tests::{
@@ -17,9 +20,6 @@ use crate::{
const BT: u32 = 16;
const BVS: &[u32] = &[16, 32];
-// MXU needs an even number of column fragments or MPP row pairing; BV16 (a single
-// 16x16 fragment) is not supported.
-const MXU_BVS: &[u32] = &[32];
#[derive(Clone, Copy)]
struct SolveCase {
@@ -199,20 +199,26 @@ fn test_tree_update_solve_cases() {
}
}
}
-}
-#[uzu_test]
-fn test_tree_update_solve_mxu_cases() {
- for &bv in MXU_BVS {
- for &use_h0 in &[true, false] {
- for &case in CASES {
- let expected = run_case::<Cpu, bf16>(case, bv, false, use_h0, DataType::BF16, bf16::from_f32);
- for_each_non_cpu_backend!(|B| {
- if <B as Backend>::Context::new().expect("context").supports_mxu() {
- let output = run_case::<B, bf16>(case, bv, true, use_h0, DataType::BF16, bf16::from_f32);
- assert_eq_float(&expected, &output, 1e-2, &format!("{} MXU BV{bv} h0={use_h0}", case.name));
+ {
+ let supports_mxu = <Metal as Backend>::Context::new().expect("context").supports_mxu();
+ let paths: &[(&str, bool)] = if supports_mxu {
+ &[("Simdgroup", false), ("MXU", true)]
+ } else {
+ &[("Simdgroup", false)]
+ };
+
+ // MXU needs an even number of column fragments or MPP row pairing; BV16
+ // (a single 16x16 fragment) is not supported.
+ for &bv in &[32] {
+ for &use_h0 in &[true, false] {
+ for &case in CASES {
+ let expected = run_case::<Cpu, bf16>(case, bv, false, use_h0, DataType::BF16, bf16::from_f32);
+ for &(path, use_mxu) in paths {
+ let output = run_case::<Metal, bf16>(case, bv, use_mxu, use_h0, DataType::BF16, bf16::from_f32);
+ assert_eq_float(&expected, &output, 1e-2, &format!("{} {path} BV{bv} h0={use_h0}", case.name));
}
- });
+ }
}
}
}
diff --git a/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs b/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
index 0cce33bdb..0457e3f95 100644
--- a/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
@@ -5,16 +5,15 @@ use num_traits::Float;
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
-use super::AttentionGemmCore;
use crate::{
array::ArrayElement,
backends::{
- common::{Backend, Context, Encoder},
+ common::{Backend, Context, Encoder, Kernels, kernel::attention_gemm::AttentionGemmCore},
cpu::Cpu,
},
data_type::DataType,
encodable_block::mixer::attention::{
- core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+ core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, AttentionCores},
state::AttentionStateType,
},
tests::{
@@ -84,23 +83,18 @@ fn get_test_data<T: ArrayElement + Float>(
fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
let context = B::Context::new().expect("Failed to create Context");
- let core = AttentionGemmCore::<B>::new(
- &AttentionCoreNewArguments {
- head_dim: input.head_dim,
- num_groups: input.num_kv_heads,
- num_q_heads: input.num_heads,
- has_sinks: false,
- is_kv_cache_ring: false,
- is_causal: input.do_causal,
- is_trie: false,
- sliding_window_size: None,
- scale: Some(input.scale),
- data_type: T::data_type(),
- },
- false,
- context.as_ref(),
- )
- .expect("Failed to create AttentionGemmCore");
+ let new_arguments = AttentionCoreNewArguments {
+ head_dim: input.head_dim,
+ num_groups: input.num_kv_heads,
+ num_q_heads: input.num_heads,
+ has_sinks: false,
+ is_kv_cache_ring: false,
+ is_causal: input.do_causal,
+ is_trie: false,
+ sliding_window_size: None,
+ scale: Some(input.scale),
+ data_type: T::data_type(),
+ };
let queries_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.queries);
let keys_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.keys);
@@ -122,7 +116,18 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
};
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- let pooled_output = core.encode(args, &mut encoder).expect("Failed to encode AttentionGemm");
+ let pooled_output =
+ if <<B as Backend>::Kernels as Kernels>::AttentionGemmCore::is_supported(&new_arguments, context.as_ref())
+ .expect("Failed to query AttentionGemm support")
+ {
+ let core = <<B as Backend>::Kernels as Kernels>::AttentionGemmCore::new(context.as_ref(), &new_arguments)
+ .expect("Failed to create AttentionGemmCore");
+ core.encode(args, &mut encoder).expect("Failed to encode AttentionGemm")
+ } else {
+ let core =
+ AttentionCores::<B>::new(new_arguments, context.as_ref()).expect("Failed to create AttentionCore");
+ core.encode(args, &mut encoder).expect("Failed to encode AttentionCore")
+ };
let mut output_allocation =
alloc_allocation::<B, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);
encoder.encode_copy(&pooled_output, .., &mut output_allocation, ..);
diff --git a/crates/backend-uzu/unit/encodable_block/attention_test.rs b/crates/backend-uzu/unit/encodable_block/attention_test.rs
index 1c67c16ba..4574612ca 100644
--- a/crates/backend-uzu/unit/encodable_block/attention_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/attention_test.rs
@@ -4,17 +4,22 @@ use ndarray::{Array4, s};
use proc_macros::uzu_test;
use test_tag::tag;
-use super::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, gemm::AttentionGemmCore};
use crate::{
backends::{
common::{
Allocation, Backend, Context, Encoder, Kernels,
- kernel::{AttentionSinglePassKernel, AttentionTwoPass1Kernel, AttentionTwoPass2Kernel},
+ kernel::{
+ AttentionSinglePassKernel, AttentionTwoPass1Kernel, AttentionTwoPass2Kernel,
+ attention_gemm::AttentionGemmCore,
+ },
},
metal::Metal,
},
data_type::DataType,
- encodable_block::mixer::attention::state::AttentionStateType,
+ encodable_block::mixer::attention::{
+ core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+ state::AttentionStateType,
+ },
tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, submit_encoder},
};
@@ -313,7 +318,8 @@ fn run_gemm_attention(
let (batch_size, num_heads, seq_len, head_dim) = queries.dim();
let (_batch_size, num_kv_heads, _seq_len, _head_dim) = keys.dim();
- let core = AttentionGemmCore::<Metal>::new(
+ let core = <<Metal as Backend>::Kernels as Kernels>::AttentionGemmCore::new(
+ context,
&AttentionCoreNewArguments {
head_dim,
num_groups: num_kv_heads,
@@ -326,8 +332,6 @@ fn run_gemm_attention(
scale: Some(scale),
data_type: DataType::F32,
},
- false,
- context,
)?;
let query_allocation = create_query_allocation(queries, context);