Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Pre-m5 attention optimizations (#1059)

uuuvn0b2a36633670
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/kv_layout.rs b/crates/uzu-engine/src/backends/common/gpu_types/kv_layout.rs
index 324cb11d4..979b2d065 100644
--- a/crates/uzu-engine/src/backends/common/gpu_types/kv_layout.rs
+++ b/crates/uzu-engine/src/backends/common/gpu_types/kv_layout.rs
@@ -1,14 +1,5 @@
-pub const TILE_KEYS: u32 = 32;
-pub const TILE_QUERIES: u32 = 16;
-pub const TILE_DIMS: u32 = 16;
-pub const FRAGMENT_BYTES: u32 = TILE_KEYS * TILE_DIMS;
-pub const SLICE_DIMS: u32 = 64;
pub const V_CODE_BIAS: i16 = 128;
-pub const GROUP_ROWS: u32 = 8;
-pub const LANE_COLS: u32 = 4;
-pub const LANE_BYTES: u32 = TILE_KEYS / GROUP_ROWS * LANE_COLS;
-
pub const WORD_BITS: u32 = 32;
pub const ROTATION_SIGN_BITS: [u32; 8] =
[0x9e3779b9, 0x85ebca6b, 0xc2b2ae35, 0x27d4eb2f, 0x165667b1, 0xbf58476d, 0x94d049bb, 0xd6e8feb8];
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs b/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
index 902858285..071b12df6 100644
--- a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
+++ b/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
@@ -14,6 +14,7 @@ pub mod hadamard_order;
pub mod kv_cache_update;
pub mod kv_layout;
pub mod matmul;
+pub mod qkv_norm;
pub mod quantization;
pub mod quantization_method;
pub mod ring;
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/qkv_norm.rs b/crates/uzu-engine/src/backends/common/gpu_types/qkv_norm.rs
new file mode 100644
index 000000000..263907162
--- /dev/null
+++ b/crates/uzu-engine/src/backends/common/gpu_types/qkv_norm.rs
@@ -0,0 +1,8 @@
+#[derive(Clone, Copy, Debug, Default)]
+#[repr(C)]
+pub struct QKVNormParams {
+ pub enabled: [u32; 3],
+ pub full_layer: [u32; 3],
+ pub epsilon: [f32; 3],
+ pub scale_offset: [f32; 3],
+}
diff --git a/crates/uzu-engine/src/backends/common/kernel/attention.rs b/crates/uzu-engine/src/backends/common/kernel/attention.rs
index 2266daa37..b3094e7fd 100644
--- a/crates/uzu-engine/src/backends/common/kernel/attention.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/attention.rs
@@ -1,17 +1,11 @@
use std::error::Error;
use crate::{
- backends::common::{Backend, BufferRef, CommandBuffer, Kernels},
+ backends::common::{Backend, BufferRef, CommandBuffer, Kernels, kernel::kv_layout::KVLayout},
data_type::DataType,
encodable_block::mixer::attention::KVCacheView,
};
-#[derive(Clone, Copy, PartialEq)]
-pub enum KVFormat {
- BF16,
- INT8,
-}
-
pub trait AttentionKernel: Sized + Send + Sync {
type Backend: Backend<Kernels: Kernels<AttentionKernel = Self>>;
type Error: Error + 'static;
@@ -21,9 +15,7 @@ pub trait AttentionKernel: Sized + Send + Sync {
config: AttentionKernelConfig,
) -> Result<Self, Self::Error>;
- fn supports_int8(&self) -> bool {
- false
- }
+ fn kv_layout(&self) -> KVLayout;
fn encode(
&self,
@@ -65,20 +57,7 @@ pub struct AttentionArguments<'a, B: Backend, TT: BufferRef<Backend = B>, GT: Bu
}
#[derive(Clone, Copy)]
-pub enum AttentionInput<QT: BufferRef, KT: BufferRef, VT: BufferRef> {
- FullPrecision(FullPrecisionInput<QT, KT, VT>),
- Int8(Int8Input<QT, KT, VT>),
-}
-
-#[derive(Clone, Copy)]
-pub struct FullPrecisionInput<QT: BufferRef, KT: BufferRef, VT: BufferRef> {
- pub queries: QT,
- pub keys: KT,
- pub values: VT,
-}
-
-#[derive(Clone, Copy)]
-pub struct Int8Input<QT: BufferRef, KT: BufferRef, VT: BufferRef> {
+pub struct AttentionInput<QT: BufferRef, KT: BufferRef, VT: BufferRef> {
pub query_codes: QT,
pub query_scales: QT,
pub k_codes: KT,
diff --git a/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs b/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs
index c672dadd8..ba5903324 100644
--- a/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs
@@ -1,89 +1,39 @@
use half::bf16;
-use crate::backends::common::gpu_types::kv_layout;
-
-pub struct Int8KVLayout {
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct KVLayout {
pub head_dim: u32,
pub num_kv_heads: u32,
+ pub key_alignment: u32,
+ pub backend_opaque_layout: u32,
}
-impl Int8KVLayout {
+impl KVLayout {
pub fn new(
head_dim: u32,
num_kv_heads: u32,
+ key_alignment: u32,
+ backend_opaque_layout: u32,
) -> Self {
Self {
head_dim,
num_kv_heads,
+ key_alignment,
+ backend_opaque_layout,
}
}
- /// Scales: [key block][head][key in block].
- #[cfg(backend = "cpu")]
- pub fn scale_index(
- &self,
- key: u32,
- head: u32,
- ) -> usize {
- ((key / kv_layout::TILE_KEYS * self.num_kv_heads + head) * kv_layout::TILE_KEYS + key % kv_layout::TILE_KEYS)
- as usize
- }
-
pub fn code_bytes(
&self,
keys: u32,
) -> usize {
- keys.next_multiple_of(kv_layout::TILE_KEYS) as usize * (self.num_kv_heads * self.head_dim) as usize
+ keys.next_multiple_of(self.key_alignment) as usize * self.num_kv_heads as usize * self.head_dim as usize
}
pub fn scale_bytes(
&self,
keys: u32,
) -> usize {
- self.code_bytes(keys) / self.head_dim as usize * size_of::<bf16>()
+ keys.next_multiple_of(self.key_alignment) as usize * self.num_kv_heads as usize * size_of::<bf16>()
}
-
- #[cfg(backend = "cpu")]
- pub fn k_code_index(
- &self,
- key: u32,
- head: u32,
- channel: u32,
- ) -> usize {
- let row = key % kv_layout::TILE_KEYS;
- let lane = mma_lane(row % kv_layout::GROUP_ROWS, channel % kv_layout::TILE_DIMS / kv_layout::LANE_COLS);
- let lane_offset = row / kv_layout::GROUP_ROWS * kv_layout::LANE_COLS + channel % kv_layout::LANE_COLS;
- ((key / kv_layout::TILE_KEYS * self.num_kv_heads + head) * kv_layout::TILE_KEYS * self.head_dim) as usize
- + (channel / kv_layout::TILE_DIMS * kv_layout::FRAGMENT_BYTES + lane * kv_layout::LANE_BYTES + lane_offset)
- as usize
- }
-
- #[cfg(backend = "cpu")]
- pub fn v_code_index(
- &self,
- key: u32,
- head: u32,
- channel: u32,
- ) -> usize {
- let (row, slice_channel) = (key % kv_layout::TILE_KEYS, channel % kv_layout::SLICE_DIMS);
- let tile = slice_channel / kv_layout::TILE_DIMS;
- let tiles = kv_layout::SLICE_DIMS / kv_layout::TILE_DIMS;
- let half_rows = kv_layout::TILE_KEYS / 2;
- let lane = mma_lane(row % kv_layout::GROUP_ROWS, slice_channel % kv_layout::TILE_DIMS / kv_layout::LANE_COLS);
- let pair = tiles * (channel / kv_layout::SLICE_DIMS) + tiles / 2 * (row / half_rows) + tile / 2;
- let lane_offset = tile % 2 * (kv_layout::LANE_BYTES / 2)
- + row % half_rows / kv_layout::GROUP_ROWS * kv_layout::LANE_COLS
- + channel % kv_layout::LANE_COLS;
- ((key / kv_layout::TILE_KEYS * self.num_kv_heads + head) * kv_layout::TILE_KEYS * self.head_dim) as usize
- + (pair * kv_layout::FRAGMENT_BYTES + lane * kv_layout::LANE_BYTES + lane_offset) as usize
- }
-}
-
-#[cfg(backend = "cpu")]
-fn mma_lane(
- row: u32,
- group: u32,
-) -> u32 {
- // Lane bits: row[2], group[1], row[1], row[0], group[0].
- ((row >> 2) << 4) | ((group >> 1) << 3) | (((row >> 1) & 1) << 2) | ((row & 1) << 1) | (group & 1)
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/mod.rs b/crates/uzu-engine/src/backends/common/kernel/mod.rs
index 5a3a3efaf..626d7a35c 100644
--- a/crates/uzu-engine/src/backends/common/kernel/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/mod.rs
@@ -15,9 +15,7 @@ pub mod radix_top_k_small;
mod trellis;
pub use activation_transform::{ActivationQuantization, ActivationTransform};
-pub use attention::{
- AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, FullPrecisionInput, Int8Input, KVFormat,
-};
+pub use attention::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig};
pub use gated_act_mul::{GatedActMul, GatedActMulSettings};
pub use matmul::ActivationFormat;
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/ancestor_attention.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/ancestor_attention.rs
index 4b83aaf08..c97bee966 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/ancestor_attention.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/ancestor_attention.rs
@@ -1,14 +1,25 @@
use half::bf16;
use uzu_engine_macros::kernel;
-use super::attention_single_pass::attention_single_pass;
-use crate::backends::common::gpu_types::weaver::MetadataIdx;
+use crate::backends::{
+ common::gpu_types::weaver::MetadataIdx,
+ cpu::kernel::attention::{
+ compute::{Row, quantize},
+ rope::apply_rope,
+ },
+};
#[kernel(AncestorAttention)]
#[variants(HEAD_DIM, 128)]
fn ancestor_attention<const HEAD_DIM: u32>(
- prefix_kv: *const bf16,
- node_kv: *mut bf16,
+ prefix_k_codes: *const i8,
+ prefix_k_scales: *const bf16,
+ prefix_v_codes: *const u8,
+ prefix_v_scales: *const bf16,
+ node_k_codes: *mut i8,
+ node_k_scales: *mut bf16,
+ node_v_codes: *mut u8,
+ node_v_scales: *mut bf16,
current_qkv: *const bf16,
cosines: *const f32,
sines: *const f32,
@@ -24,115 +35,107 @@ fn ancestor_attention<const HEAD_DIM: u32>(
max_depth: u32,
scale: f32,
#[specialize] num_heads: u32,
+ #[specialize] backend_opaque_layout: u32,
) {
- const QKV_COMPONENTS: usize = 3;
- const KEY_COMPONENT: usize = 1;
- const VALUE_COMPONENT: usize = 2;
- let head_dim = HEAD_DIM as usize;
- let num_heads = num_heads as usize;
- let model_dim = num_heads * head_dim;
- let qkv_width = QKV_COMPONENTS * model_dim;
- let prefix_length = prefix_length as usize;
- let node_capacity = node_capacity as usize;
- let half_dim = head_dim / 2;
- let row_count = rows as usize;
-
- for row in 0..row_count {
+ let dim = HEAD_DIM as usize;
+ let model_dim = num_heads as usize * dim;
+ assert_eq!(backend_opaque_layout, 0);
+ for row in 0..rows as usize {
unsafe {
- let current_row = current_qkv.add(row * qkv_width);
-
- let depth = *node_metadata.add(MetadataIdx::Depth as usize * row_count + row);
+ let depth = *node_metadata.add(MetadataIdx::Depth as usize * rows as usize + row);
assert!(depth < max_depth, "node metadata depth must be rope-safe");
- let position = depth 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);
+ for head in 0..num_heads {
+ let qkv = current_qkv.add(row * 3 * model_dim + head as usize * dim);
+ let rotate = |component| {
+ (0..dim)
+ .map(|c| {
+ apply_rope(qkv.add(component * model_dim), cosines, sines, depth as usize + 1, c, dim)
+ .to_f32()
+ })
+ .collect()
+ };
+ let (q, qs) = quantize(rotate(0));
+ let (k, ks) = quantize(rotate(1));
+ let (v, vs) = quantize((0..dim).map(|c| (*qkv.add(2 * model_dim + c)).to_f32()).collect());
+ let ancestors = *ancestor_counts.add(row);
+ let mut result = Row::new(dim, None);
+ for index in 0..prefix_length + ancestors + 1 {
+ let own = index == prefix_length + ancestors;
+ let prefix = index < prefix_length;
+ let slot = if prefix || own {
+ index
+ } else {
+ *ancestor_indices.add(row * ancestor_stride as usize + (index - prefix_length) as usize)
+ };
+ if !prefix && !own {
+ assert!(slot < node_capacity);
+ }
+ let kc = if prefix {
+ prefix_k_codes
+ } else {
+ node_k_codes
+ };
+ let vc = if prefix {
+ prefix_v_codes
+ } else {
+ node_v_codes
+ };
+ let kv_row = (slot * num_heads + head) as usize;
+ let key_scale = if own {
+ ks
+ } else {
+ *(if prefix {
+ prefix_k_scales
+ } else {
+ node_k_scales
+ })
+ .add(kv_row)
}
+ .to_f32();
+ let value_scale = if own {
+ vs
+ } else {
+ *(if prefix {
+ prefix_v_scales
+ } else {
+ node_v_scales
+ })
+ .add(kv_row)
+ }
+ .to_f32();
+ let dot: i32 = (0..dim)
+ .map(|c| {
+ i32::from(q[c])
+ * i32::from(if own {
+ k[c]
+ } else {
+ *kc.add(kv_row * dim + c)
+ })
+ })
+ .sum();
+ result.add(dot as f32 * qs.to_f32() * key_scale * scale, |c| {
+ (if own {
+ i32::from(v[c])
+ } else {
+ i32::from(*vc.add(kv_row * dim + c)) - 128
+ }) as f32
+ * value_scale
+ });
+ }
+ if node_capacity > 0 {
+ let slot = *node_indices.add(row);
+ assert!(slot < node_capacity);
+ let kv_row = (slot * num_heads + head) as usize;
+ for c in 0..dim {
+ *node_k_codes.add(kv_row * dim + c) = k[c];
+ *node_v_codes.add(kv_row * dim + c) = (i16::from(v[c]) + 128) as u8;
+ }
+ *node_k_scales.add(kv_row) = ks;
+ *node_v_scales.add(kv_row) = vs;
+ }
+ for (c, value) in result.finish().into_iter().enumerate() {
+ *output.add((row * num_heads as usize + head as usize) * dim + c) = bf16::from_f32(value);
}
- 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];
- let mut values = vec![bf16::ZERO; length * model_dim];
- std::ptr::copy_nonoverlapping(prefix_kv, keys.as_mut_ptr(), prefix_length * model_dim);
- std::ptr::copy_nonoverlapping(
- prefix_kv.add(prefix_length * model_dim),
- values.as_mut_ptr(),
- prefix_length * model_dim,
- );
- for offset in 0..ancestor_count {
- let ancestor = *ancestor_indices.add(row * ancestor_stride as usize + offset) as usize;
- assert!(ancestor < node_capacity, "ancestor slot exceeds tree slot count");
- std::ptr::copy_nonoverlapping(
- node_kv.add(ancestor * model_dim),
- keys.as_mut_ptr().add((prefix_length + offset) * model_dim),
- model_dim,
- );
- std::ptr::copy_nonoverlapping(
- node_kv.add(node_capacity * model_dim + ancestor * model_dim),
- values.as_mut_ptr().add((prefix_length + offset) * model_dim),
- model_dim,
- );
- }
- std::ptr::copy_nonoverlapping(
- rotated_keys.as_ptr(),
- keys.as_mut_ptr().add((length - 1) * model_dim),
- model_dim,
- );
- std::ptr::copy_nonoverlapping(
- current_row.add(VALUE_COMPONENT * model_dim),
- values.as_mut_ptr().add((length - 1) * model_dim),
- model_dim,
- );
- attention_single_pass::<bf16, HEAD_DIM>(
- rotated_queries.as_ptr(),
- keys.as_ptr(),
- values.as_ptr(),
- output.add(row * num_heads * head_dim),
- 1,
- length as u32,
- HEAD_DIM,
- model_dim as u32,
- HEAD_DIM,
- model_dim as u32,
- None,
- scale,
- None,
- None,
- None,
- num_heads as u32,
- 1,
- false,
- false,
- false,
- false,
- false,
- );
- if node_capacity > 0 {
- let node = *node_indices.add(row) as usize;
- assert!(node < node_capacity, "node slot exceeds tree slot count");
- 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),
- model_dim,
- );
}
}
}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs
deleted file mode 100644
index 4da298f46..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs
+++ /dev/null
@@ -1,129 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::data_type::DataTypeRepr;
-
-pub(super) fn apply_rope<ElementT: DataTypeRepr + Float>(
- head: *const ElementT,
- cosines: *const (impl DataTypeRepr + Float),
- sines: *const (impl DataTypeRepr + Float),
- batch_idx: usize,
- head_dim_idx: usize,
- rope_dim: usize,
-) -> ElementT {
- let half_rope_dim = rope_dim / 2;
- let paired_idx = if head_dim_idx < half_rope_dim {
- head_dim_idx + half_rope_dim
- } else {
- head_dim_idx - half_rope_dim
- };
- let input = unsafe { (*head.add(head_dim_idx)).to_f32().unwrap() };
- let paired = unsafe { (*head.add(paired_idx)).to_f32().unwrap() };
- let signed_paired = if head_dim_idx < half_rope_dim {
- -paired
- } else {
- paired
- };
- let cos_val = unsafe { (*cosines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
- let sin_val = unsafe { (*sines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
-
- ElementT::from(input * cos_val + signed_paired * sin_val).unwrap()
-}
-
-#[kernel(AttentionPrepare)]
-#[variants(ElementT, bf16)]
-#[variants(RopeT, f32)]
-pub fn attention_prepare<ElementT: DataTypeRepr + Float, RopeT: DataTypeRepr + Float>(
- qkvg: *const ElementT,
- queries: *mut ElementT,
- #[optional(has_kv)] keys: Option<*mut ElementT>,
- #[optional(has_kv)] values: Option<*mut ElementT>,
- #[optional(has_rope)] cosines: Option<*const RopeT>,
- #[optional(has_rope)] sines: Option<*const RopeT>,
- num_q_heads: u32,
- #[optional(has_kv)] num_kv_heads: Option<u32>,
- head_dim: u32,
- #[optional(has_rope)] rope_dim: Option<u32>,
- #[optional(has_kv)] kv_token_offset: Option<u32>,
- input_row_stride: u32,
- batch_dim: u32,
- #[specialize] has_kv: bool,
- #[specialize] has_rope: bool,
-) {
- assert!(num_q_heads > 0 || has_kv, "attention prepare without KV requires at least one query head");
- assert!(head_dim > 0, "attention prepare requires nonzero head_dim");
- assert_eq!(keys.is_some(), has_kv, "attention prepare keys presence mismatch");
- assert_eq!(values.is_some(), has_kv, "attention prepare values presence mismatch");
- assert_eq!(num_kv_heads.is_some(), has_kv, "attention prepare num_kv_heads presence mismatch");
- assert_eq!(kv_token_offset.is_some(), has_kv, "attention prepare kv_token_offset presence mismatch");
- assert_eq!(cosines.is_some(), has_rope, "attention prepare cosines presence mismatch");
- assert_eq!(sines.is_some(), has_rope, "attention prepare sines presence mismatch");
- assert_eq!(rope_dim.is_some(), has_rope, "attention prepare rope_dim presence mismatch");
-
- let (keys, values, num_kv_heads, kv_token_offset) =
- if let (Some(keys), Some(values), Some(num_kv_heads), Some(kv_token_offset)) =
- (keys, values, num_kv_heads, kv_token_offset)
- {
- assert!(num_kv_heads > 0, "attention prepare has_kv requires nonzero num_kv_heads");
- (keys, values, num_kv_heads as usize, kv_token_offset as usize)
- } else {
- (std::ptr::null_mut(), std::ptr::null_mut(), 0, 0)
- };
-
- let (cosines, sines, rope_dim) = if let (Some(cosines), Some(sines), Some(rope_dim)) = (cosines, sines, rope_dim) {
- assert!(rope_dim > 0, "attention prepare has_rope requires nonzero rope_dim");
- assert!(rope_dim <= head_dim, "attention prepare rope_dim exceeds head_dim");
- assert!(rope_dim.is_multiple_of(2), "attention prepare rope_dim must be even");
- (cosines, sines, rope_dim as usize)
- } else {
- (std::ptr::null(), std::ptr::null(), 0)
- };
-
- let num_q_heads = num_q_heads as usize;
- let head_dim = head_dim as usize;
- let batch_dim = batch_dim as usize;
- let input_row_stride = input_row_stride as usize;
- let total_heads = if has_kv {
- num_q_heads + num_kv_heads * 2
- } else {
- num_q_heads
- };
- assert!(input_row_stride >= total_heads * head_dim, "attention prepare row stride is too small");
-
- for batch_idx in 0..batch_dim {
- for head_idx in 0..total_heads {
- let qkvg_head = unsafe { qkvg.add(batch_idx * input_row_stride + head_idx * head_dim) };
- let is_query = !has_kv || head_idx < num_q_heads;
- let is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;
-
- for head_dim_idx in 0..head_dim {
- let mut element = unsafe { *qkvg_head.add(head_dim_idx) };
- if has_rope && head_dim_idx < rope_dim && (is_query || is_key) {
- element = apply_rope(qkvg_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);
- }
-
- if is_query {
- let query_offset = head_idx * batch_dim * head_dim + batch_idx * head_dim + head_dim_idx;
- unsafe {
- *queries.add(query_offset) = element;
- }
- } else if is_key {
- let key_offset = (kv_token_offset + batch_idx) * num_kv_heads * head_dim
- + (head_idx - num_q_heads) * head_dim
- + head_dim_idx;
- unsafe {
- *keys.add(key_offset) = element;
- }
- } else {
- let value_offset = (kv_token_offset + batch_idx) * num_kv_heads * head_dim
- + (head_idx - num_q_heads - num_kv_heads) * head_dim
- + head_dim_idx;
- unsafe {
- *values.add(value_offset) = element;
- }
- }
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_single_pass.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_single_pass.rs
deleted file mode 100644
index 73a887dd8..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_single_pass.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::{
- backends::{common::gpu_types::trie::TrieNode, cpu::kernel::attention::mask::should_use_key},
- data_type::DataTypeRepr,
-};
-
-#[kernel(AttentionSinglePass)]
-#[variants(T, f32, bf16)]
-#[variants(HEAD_DIM, 64, 128, 256, 512)]
-pub fn attention_single_pass<T: DataTypeRepr + Float, const HEAD_DIM: u32>(
- queries: *const T,
- keys: *const T,
- values: *const T,
- out: *mut T,
- gqa_factor: u32,
- sequence_length: u32,
- k_head_stride: u32,
- k_seq_stride: u32,
- v_head_stride: u32,
- v_seq_stride: u32,
- #[optional(is_kv_cache_ring)] ring_params: Option<crate::backends::common::gpu_types::ring::RingParams>,
- scale: f32,
- #[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] has_sinks: bool,
- #[specialize] is_kv_cache_ring: bool,
- #[specialize] is_causal: bool,
- #[specialize] is_trie: bool,
- #[specialize] is_sliding_window: bool,
-) {
- assert_eq!(ring_params.is_some(), is_kv_cache_ring);
- assert_eq!(sliding_window_size.is_some(), is_sliding_window);
-
- let value_dim = HEAD_DIM;
-
- let prefix_length = sequence_length - suffix_length;
- let suffix_position = if let Some(ring_params) = ring_params {
- ring_params.ring_length
- } else {
- prefix_length
- };
-
- for head_idx in 0..num_heads {
- for q_seq_idx in 0..suffix_length {
- let kv_head_idx = head_idx / gqa_factor;
- let o_offset = q_seq_idx * num_heads + head_idx;
- let q_offset = head_idx * suffix_length + q_seq_idx;
-
- let query_position = if is_trie {
- let trie_node = unsafe { &*trie.unwrap().add(q_seq_idx as usize) };
- suffix_position + trie_node.height
- } else {
- suffix_position + q_seq_idx
- };
-
- let queries: *const T = unsafe { queries.add((q_offset * HEAD_DIM) as usize) };
- let keys: *const T = unsafe { keys.add((kv_head_idx * k_head_stride) as usize) };
- let values: *const T = unsafe { values.add((kv_head_idx * v_head_stride) as usize) };
- let out: *mut T = unsafe { out.add((o_offset * value_dim) as usize) };
-
- // Read the query and 0 the output accumulator
- let mut q = vec![0.0f32; HEAD_DIM as usize];
- let mut o = vec![0.0f32; HEAD_DIM as usize];
- for j in 0..HEAD_DIM as usize {
- q[j] = scale * unsafe { *queries.add(j) }.to_f32().unwrap();
- }
-
- let mut max_score = f32::NEG_INFINITY;
- let mut sum_exp_score = 0.0f32;
- if has_sinks {
- let q_head_idx = head_idx % num_heads;
- max_score = unsafe { *sinks.unwrap().add(q_head_idx as usize) }.to_f32().unwrap();
- sum_exp_score = 1.0;
- }
-
- // For each key
- for i in 0..sequence_length {
- if should_use_key(
- ring_params,
- trie,
- sliding_window_size,
- q_seq_idx,
- prefix_length,
- suffix_position,
- query_position,
- i,
- is_causal,
- ) {
- let keys = unsafe { keys.add((i * k_seq_stride) as usize) };
-
- // Compute the i-th score
- let mut score = 0.0f32;
- for j in 0..HEAD_DIM as usize {
- score += q[j] * unsafe { *keys.add(j) }.to_f32().unwrap();
- }
-
- // Update the accumulators
- 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_score = sum_exp_score * factor + exp_score;
-
- // Update the output accumulator
- let values = unsafe { values.add((i * v_seq_stride) as usize) };
- for j in 0..HEAD_DIM as usize {
- o[j] = o[j] * factor + exp_score * unsafe { *values.add(j) }.to_f32().unwrap();
- }
- }
- }
-
- // Write the output
- for j in 0..HEAD_DIM as usize {
- unsafe {
- *out.add(j) = T::from(o[j] / sum_exp_score).unwrap();
- }
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/compute.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/compute.rs
new file mode 100644
index 000000000..2b25ae537
--- /dev/null
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/compute.rs
@@ -0,0 +1,180 @@
+use half::bf16;
+use num_traits::AsPrimitive;
+
+use crate::{
+ backends::{
+ common::{
+ BufferRef, CommandBufferEncoding,
+ gpu_types::{kv_layout, trie::TrieNode},
+ kernel::{AttentionArguments, AttentionInput, AttentionKernelConfig},
+ },
+ cpu::{
+ Cpu,
+ buffer::CpuBufferExt,
+ command_buffer::CpuCommandBufferEncoding,
+ error::CpuError,
+ kernel::{activation_transform::hadamard_transform, attention::mask::should_use_key},
+ },
+ },
+ utils::{
+ dispatch_dtype::dispatch_dtype,
+ pointers::{SendPtr, SendPtrMut},
+ },
+};
+
+pub(super) fn sign(channel: usize) -> f32 {
+ if (kv_layout::ROTATION_SIGN_BITS[channel / 32 % 8] >> (channel % 32)) & 1 != 0 {
+ -1.0
+ } else {
+ 1.0
+ }
+}
+
+pub(super) fn quantize(mut values: Vec<f32>) -> (Vec<i8>, bf16) {
+ for (channel, value) in values.iter_mut().enumerate() {
+ *value *= sign(channel);
+ }
+ hadamard_transform(&mut values);
+ let maximum = values.iter().fold(0.0f32, |m, v| m.max(v.abs()));
+ let scale = bf16::from_f32(if maximum > 0.0 {
+ maximum / 127.0
+ } else {
+ 1.0
+ });
+ (values.into_iter().map(|v| (v / scale.to_f32()).round_ties_even().clamp(-127.0, 127.0) as i8).collect(), scale)
+}
+
+pub(super) struct Row {
+ maximum: f32,
+ denominator: f32,
+ values: Vec<f32>,
+}
+
+impl Row {
+ pub(super) fn new(
+ head_dim: usize,
+ sink: Option<f32>,
+ ) -> Self {
+ Self {
+ maximum: sink.unwrap_or(f32::NEG_INFINITY),
+ denominator: if sink.is_some() {
+ 1.0
+ } else {
+ 0.0
+ },
+ values: vec![0.0; head_dim],
+ }
+ }
+
+ pub(super) fn add(
+ &mut self,
+ score: f32,
+ value: impl Fn(usize) -> f32,
+ ) {
+ let maximum = self.maximum.max(score);
+ let correction = (self.maximum - maximum).exp();
+ let weight = (score - maximum).exp();
+ self.denominator = self.denominator * correction + weight;
+ for (channel, sum) in self.values.iter_mut().enumerate() {
+ *sum = *sum * correction + weight * value(channel);
+ }
+ self.maximum = maximum;
+ }
+
+ pub(super) fn finish(mut self) -> Vec<f32> {
+ if self.denominator > 0.0 {
+ for value in &mut self.values {
+ *value /= self.denominator;
+ }
+ }
+ hadamard_transform(&mut self.values);
+ for (channel, value) in self.values.iter_mut().enumerate() {
+ *value *= sign(channel);
+ }
+ self.values
+ }
+}
+
+pub(super) fn encode(
+ input: AttentionInput<impl BufferRef<Backend = Cpu>, impl BufferRef<Backend = Cpu>, impl BufferRef<Backend = Cpu>>,
+ arguments: AttentionArguments<'_, Cpu, impl BufferRef<Backend = Cpu>, impl BufferRef<Backend = Cpu>>,
+ config: AttentionKernelConfig,
+ command_buffer: &mut CpuCommandBufferEncoding,
+) -> Result<<Cpu as crate::backends::common::Backend>::ScratchBuffer, CpuError> {
+ fn ptr(view: impl BufferRef<Backend = Cpu>) -> SendPtr<u8> {
+ let (buffer, range) = view.parts();
+ SendPtr(buffer.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_add(range.start))
+ }
+ let output = command_buffer.allocate_scratch_for_shape(
+ &[arguments.suffix_length, config.num_q_heads, config.head_dim],
+ config.data_type,
+ )?;
+ let output_ptr = SendPtrMut(ptr(&output).as_ptr().cast_mut());
+ let q_codes = ptr(input.query_codes);
+ let q_scales = ptr(input.query_scales);
+ let k_codes = ptr(input.k_codes);
+ let k_scales = ptr(input.k_scales);
+ let v_codes = ptr(input.v_codes);
+ let v_scales = ptr(input.v_scales);
+ let trie = arguments.trie.map(ptr);
+ let sinks = arguments.sinks.map(ptr);
+ let gate = arguments.gate.map(ptr);
+ let prefix = arguments.cache.prefix_len();
+ let ring = arguments.cache.ring_params();
+ let suffix = arguments.suffix_length;
+ command_buffer.push_command(move || {
+ let dim = config.head_dim as usize;
+ let gqa = config.num_q_heads / config.num_groups;
+ let scale = config.scale.unwrap_or(1.0 / (dim as f32).sqrt());
+ let suffix_position = ring.map_or(prefix, |r| r.ring_length);
+ let trie = trie.map(|p| p.as_ptr().cast::<TrieNode>());
+ dispatch_dtype!(|(T: config.data_type)| {
+ for head in 0..config.num_q_heads {
+ let kv_head = head / gqa;
+ for query in 0..suffix {
+ let qrow = (head * suffix + query) as usize;
+ unsafe {
+ let qs = (*q_scales.as_ptr().cast::<bf16>().add(qrow)).to_f32();
+ let position = suffix_position + trie.map_or(query, |p| (*p.add(query as usize)).height);
+ let mut row = Row::new(dim, sinks.map(|p| (*p.as_ptr().cast::<T>().add(head as usize)).as_()));
+ for key in 0..prefix + suffix {
+ if !should_use_key(
+ ring, trie, config.sliding_window_size, query, prefix,
+ suffix_position, position, key, config.is_causal,
+ ) {
+ continue;
+ }
+ let kv_row = (key * config.num_groups + kv_head) as usize;
+ let dot: i32 = (0..dim)
+ .map(|c| {
+ let q = *q_codes.as_ptr().cast::<i8>().add(qrow * dim + c);
+ let k = *k_codes.as_ptr().cast::<i8>()
+ .add(kv_row * dim + c);
+ i32::from(q) * i32::from(k)
+ })
+ .sum();
+ let ks = (*k_scales.as_ptr().cast::<bf16>().add(kv_row)).to_f32();
+ let vs = (*v_scales.as_ptr().cast::<bf16>().add(kv_row)).to_f32();
+ row.add(dot as f32 * qs * ks * scale, |c| {
+ let code = *v_codes.as_ptr().add(kv_row * dim + c);
+ (i32::from(code) - 128) as f32 * vs
+ });
+ }
+ for (c, mut value) in row.finish().into_iter().enumerate() {
+ if let (Some(gate), Some(stride)) = (gate, config.gate_row_stride) {
+ let index = (query * stride + head * config.head_dim) as usize + c;
+ let g: f32 = (*gate.as_ptr().cast::<T>().add(index)).as_();
+ let rounded: T = value.as_();
+ value = rounded.as_();
+ value /= 1.0 + (-g).exp();
+ }
+ let index = (query * config.num_q_heads + head) as usize * dim + c;
+ *output_ptr.as_ptr().cast::<T>().add(index) = value.as_();
+ }
+ }
+ }
+ }
+ });
+ });
+ Ok(output)
+}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/kv_cache_update.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/kv_cache_update.rs
index 51be1992f..3165def47 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/kv_cache_update.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/kv_cache_update.rs
@@ -1,34 +1,8 @@
use half::bf16;
-use num_traits::Float;
use uzu_engine_macros::kernel;
-use crate::{backends::common::kernel::kv_layout::Int8KVLayout, data_type::DataTypeRepr};
-
#[kernel(KVCacheUpdate)]
-#[variants(T, f32, bf16)]
-pub fn kv_cache_update<T: DataTypeRepr + Float>(
- in_place_keys: *mut T,
- in_place_values: *mut T,
- copies: &[crate::backends::common::gpu_types::kv_cache_update::Copy],
- copy_count: u32,
- element_dim: u32,
-) {
- let element_dim = element_dim as usize;
-
- for element_idx in 0..element_dim {
- for i in 0..copy_count as usize {
- let source_idx = (copies[i].source as usize) * element_dim + element_idx;
- let dest_idx = (copies[i].destination as usize) * element_dim + element_idx;
- unsafe {
- *in_place_keys.add(dest_idx) = *in_place_keys.add(source_idx);
- *in_place_values.add(dest_idx) = *in_place_values.add(source_idx);
- }
- }
- }
-}
-
-#[kernel(KVCacheUpdateInt8)]
-pub fn kv_cache_update_int8(
+pub fn kv_cache_update(
in_place_k_codes: *mut i8,
in_place_v_codes: *mut u8,
in_place_k_scales: *mut bf16,
@@ -37,26 +11,20 @@ pub fn kv_cache_update_int8(
copy_count: u32,
#[specialize] head_dim: u32,
#[specialize] num_kv_heads: u32,
+ #[specialize] backend_opaque_layout: u32,
) {
- let layout = Int8KVLayout::new(head_dim, num_kv_heads);
+ assert_eq!(backend_opaque_layout, 0);
+ let row_width = (num_kv_heads * head_dim) as usize;
for copy in copies.iter().take(copy_count as usize) {
- for head in 0..num_kv_heads {
- for channel in 0..head_dim {
- let source_k = layout.k_code_index(copy.source, head, channel);
- let destination_k = layout.k_code_index(copy.destination, head, channel);
- let source_v = layout.v_code_index(copy.source, head, channel);
- let destination_v = layout.v_code_index(copy.destination, head, channel);
- unsafe {
- *in_place_k_codes.add(destination_k) = *in_place_k_codes.add(source_k);
- *in_place_v_codes.add(destination_v) = *in_place_v_codes.add(source_v);
- }
- }
- let source = layout.scale_index(copy.source, head);
- let destination = layout.scale_index(copy.destination, head);
- unsafe {
- *in_place_k_scales.add(destination) = *in_place_k_scales.add(source);
- *in_place_v_scales.add(destination) = *in_place_v_scales.add(source);
- }
+ let source = copy.source as usize * row_width;
+ let destination = copy.destination as usize * row_width;
+ unsafe {
+ std::ptr::copy(in_place_k_codes.add(source), in_place_k_codes.add(destination), row_width);
+ std::ptr::copy(in_place_v_codes.add(source), in_place_v_codes.add(destination), row_width);
+ let source = (copy.source * num_kv_heads) as usize;
+ let destination = (copy.destination * num_kv_heads) as usize;
+ std::ptr::copy(in_place_k_scales.add(source), in_place_k_scales.add(destination), num_kv_heads as usize);
+ std::ptr::copy(in_place_v_scales.add(source), in_place_v_scales.add(destination), num_kv_heads as usize);
}
}
}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs
index bb9b0135d..01fa0e672 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs
@@ -1,22 +1,17 @@
use crate::backends::common::Backend;
pub mod ancestor_attention;
-pub mod attention_prepare;
-pub mod attention_single_pass;
pub mod kv_cache_update;
-pub mod prepare_int8;
-pub mod qkv_norm;
-pub mod sigmoid_gate;
+pub mod prepare;
+mod compute;
mod mask;
+mod rope;
use crate::backends::{
common::{
- BufferRef, CommandBufferEncoding,
- kernel::{
- AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, AttentionSinglePassKernel,
- SigmoidGateKernel,
- },
+ BufferRef,
+ kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, kv_layout::KVLayout},
},
cpu::{Cpu, command_buffer::CpuCommandBufferEncoding, context::CpuContext, error::CpuError},
};
@@ -38,6 +33,10 @@ impl AttentionKernel for AttentionCpuKernel {
})
}
+ fn kv_layout(&self) -> KVLayout {
+ KVLayout::new(self.config.head_dim, self.config.num_groups, 1, 0)
+ }
+
fn encode(
&self,
input: AttentionInput<
@@ -48,59 +47,6 @@ impl AttentionKernel for AttentionCpuKernel {
arguments: AttentionArguments<'_, Cpu, impl BufferRef<Backend = Cpu>, impl BufferRef<Backend = Cpu>>,
command_buffer: &mut CpuCommandBufferEncoding,
) -> Result<<Cpu as Backend>::ScratchBuffer, CpuError> {
- let AttentionInput::FullPrecision(input) = input else {
- return Err(CpuError::NotSupported);
- };
- let config = self.config;
- let mut output = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, config.head_dim],
- config.data_type,
- )?;
-
- let single_pass = <attention_single_pass::AttentionSinglePassCpuKernel as AttentionSinglePassKernel>::new(
- command_buffer.context(),
- config.data_type,
- config.head_dim,
- config.has_sinks,
- config.is_kv_cache_ring,
- config.is_causal,
- arguments.trie.is_some(),
- config.sliding_window_size.is_some(),
- )?;
- {
- let command_buffer = &mut *command_buffer.debug_group("attention core");
- single_pass.encode(
- input.queries,
- input.keys,
- input.values,
- &mut output,
- config.num_q_heads / config.num_groups,
- arguments.cache.prefix_len() + arguments.suffix_length,
- config.head_dim,
- config.num_groups * config.head_dim,
- config.head_dim,
- config.num_groups * config.head_dim,
- arguments.cache.ring_params(),
- config.scale.unwrap_or(1.0 / (config.head_dim as f32).sqrt()),
- arguments.trie,
- config.sliding_window_size,
- arguments.sinks,
- config.num_q_heads,
- arguments.suffix_length,
- command_buffer,
- );
- }
- if let (Some(gate), Some(gate_row_stride)) = (arguments.gate, config.gate_row_stride) {
- <sigmoid_gate::SigmoidGateCpuKernel as SigmoidGateKernel>::new(command_buffer.context(), config.data_type)?
- .encode(
- gate,
- &mut output,
- config.num_q_heads * config.head_dim,
- arguments.suffix_length,
- gate_row_stride,
- command_buffer,
- );
- }
- Ok(output)
+ compute::encode(input, arguments, self.config, command_buffer)
}
}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare.rs
new file mode 100644
index 000000000..9e1c287fa
--- /dev/null
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare.rs
@@ -0,0 +1,146 @@
+use half::bf16;
+use num_traits::Float;
+use uzu_engine_macros::kernel;
+
+use crate::{
+ backends::{
+ common::gpu_types::{kv_layout, qkv_norm::QKVNormParams},
+ cpu::kernel::{
+ activation_transform::{INT8_SYMMETRIC_QUANTIZATION_MAXIMUM as INT8_MAX, hadamard_transform},
+ attention::rope::apply_rope,
+ },
+ },
+ data_type::DataTypeRepr,
+};
+
+#[kernel(AttentionPrepare)]
+#[variants(ElementT, bf16, f32)]
+#[variants(RopeT, f32)]
+#[variants(HEAD_DIM, 64, 128, 256, 512)]
+pub fn attention_prepare<ElementT: DataTypeRepr + Float, RopeT: DataTypeRepr + Float, const HEAD_DIM: u32>(
+ qkvg: *const ElementT,
+ q_codes: *mut i8,
+ q_scales: *mut bf16,
+ #[optional(append_kv)] k_codes: Option<*mut i8>,
+ #[optional(append_kv)] k_scales: Option<*mut bf16>,
+ #[optional(append_kv)] v_codes: Option<*mut u8>,
+ #[optional(append_kv)] v_scales: Option<*mut bf16>,
+ #[optional(has_rope)] cosines: Option<*const RopeT>,
+ #[optional(has_rope)] sines: Option<*const RopeT>,
+ #[optional(has_query_norm_scales)] query_norm_scales: Option<*const f32>,
+ #[optional(has_key_norm_scales)] key_norm_scales: Option<*const f32>,
+ #[optional(has_value_norm_scales)] value_norm_scales: Option<*const f32>,
+ norm_params: QKVNormParams,
+ num_q_heads: u32,
+ #[optional(has_rope)] rope_dim: Option<u32>,
+ kv_token_offset: u32,
+ input_row_stride: u32,
+ suffix_length: u32,
+ query_rows: u32,
+ #[specialize] has_rope: bool,
+ #[specialize] num_kv_heads: u32,
+ #[specialize] backend_opaque_layout: u32,
+ #[specialize] append_kv: bool,
+ #[specialize] has_query_norm_scales: bool,
+ #[specialize] has_key_norm_scales: bool,
+ #[specialize] has_value_norm_scales: bool,
+) {
+ let head_dim = HEAD_DIM as usize;
+ let rope_dim = if has_rope {
+ rope_dim.unwrap() as usize
+ } else {
+ 0
+ };
+ assert_eq!(backend_opaque_layout, 0);
+ let mut values = vec![0.0f32; head_dim];
+ let mut normalized = if norm_params.enabled.iter().any(|&enabled| enabled != 0) {
+ vec![ElementT::zero(); head_dim]
+ } else {
+ Vec::new()
+ };
+ let gqa_factor = num_q_heads / num_kv_heads;
+ let v_head_start = num_q_heads + num_kv_heads;
+ for head in 0..v_head_start + num_kv_heads {
+ let is_query = head < num_q_heads;
+ if !append_kv && !is_query {
+ continue;
+ }
+ let is_key = !is_query && head < v_head_start;
+ let (kv_head, scales) = match (is_query, is_key) {
+ (true, _) => (0, Some(q_scales)),
+ (_, true) => (head - num_q_heads, k_scales),
+ _ => (head - v_head_start, v_scales),
+ };
+ let (norm, norm_scales) = if is_query {
+ (0, has_query_norm_scales.then(|| query_norm_scales.unwrap()))
+ } else if is_key {
+ (1, has_key_norm_scales.then(|| key_norm_scales.unwrap()))
+ } else {
+ (2, has_value_norm_scales.then(|| value_norm_scales.unwrap()))
+ };
+ for token in 0..suffix_length {
+ let mut source = unsafe { qkvg.add((token * input_row_stride + head * HEAD_DIM) as usize) };
+ if norm_params.enabled[norm] != 0 {
+ let input = unsafe { std::slice::from_raw_parts(source, head_dim) };
+ let sum: f32 = input.iter().map(|v| v.to_f32().unwrap().powi(2)).sum();
+ let inverse_rms = (sum / head_dim as f32 + norm_params.epsilon[norm]).sqrt().recip();
+ for (channel, output) in normalized.iter_mut().enumerate() {
+ let value = input[channel].to_f32().unwrap() * inverse_rms;
+ *output = if let Some(scales) = norm_scales {
+ let scale = unsafe { *scales.add(channel) } + norm_params.scale_offset[norm];
+ if norm_params.full_layer[norm] != 0 {
+ ElementT::from(value * scale).unwrap()
+ } else {
+ ElementT::from(value).unwrap() * ElementT::from(scale).unwrap()
+ }
+ } else {
+ ElementT::from(value).unwrap()
+ };
+ }
+ source = normalized.as_ptr();
+ }
+ for (channel, value) in values.iter_mut().enumerate() {
+ let element = if (is_query || is_key) && channel < rope_dim {
+ apply_rope(source, cosines.unwrap(), sines.unwrap(), token as usize, channel, rope_dim)
+ } else {
+ unsafe { *source.add(channel) }
+ }
+ .to_f32()
+ .unwrap();
+ let sign_word = kv_layout::ROTATION_SIGN_BITS[channel / kv_layout::WORD_BITS as usize % 8];
+ let flip_sign = (sign_word >> (channel % kv_layout::WORD_BITS as usize)) & 1 != 0;
+ *value = if flip_sign {
+ -element
+ } else {
+ element
+ };
+ }
+ hadamard_transform(&mut values);
+ let maximum = values.iter().fold(0.0f32, |maximum, value| maximum.max(value.abs()));
+ let scale = bf16::from_f32(if maximum > 0.0 {
+ maximum / INT8_MAX
+ } else {
+ 1.0
+ });
+ let scale_index = if is_query {
+ ((head / gqa_factor) * query_rows + (head % gqa_factor) * suffix_length + token) as usize
+ } else {
+ ((kv_token_offset + token) * num_kv_heads + kv_head) as usize
+ };
+ for (channel, &value) in values.iter().enumerate() {
+ let code = (value / scale.to_f32()).round_ties_even().clamp(-INT8_MAX, INT8_MAX) as i8;
+ unsafe {
+ if is_query {
+ *q_codes.add(scale_index * head_dim + channel) = code;
+ } else if is_key {
+ *k_codes.unwrap().add(scale_index * head_dim + channel) = code;
+ } else {
+ *v_codes.unwrap().add(scale_index * head_dim + channel) =
+ (i16::from(code) + kv_layout::V_CODE_BIAS) as u8;
+ }
+ }
+ }
+ unsafe { *scales.unwrap().add(scale_index) = scale };
+ }
+ }
+}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare_int8.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare_int8.rs
deleted file mode 100644
index 180a1c1ac..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare_int8.rs
+++ /dev/null
@@ -1,118 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use super::attention_prepare::apply_rope;
-use crate::{
- backends::{
- common::{gpu_types::kv_layout, kernel::kv_layout::Int8KVLayout},
- cpu::kernel::activation_transform::{INT8_SYMMETRIC_QUANTIZATION_MAXIMUM as INT8_MAX, hadamard_transform},
- },
- data_type::DataTypeRepr,
-};
-
-#[kernel(AttentionPrepareInt8)]
-#[variants(ElementT, bf16)]
-#[variants(RopeT, f32)]
-#[variants(HEAD_DIM, 128, 256)]
-pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRepr + Float, const HEAD_DIM: u32>(
- qkvg: *const ElementT,
- #[optional(!quantize_queries)] queries: Option<*mut ElementT>,
- #[optional(quantize_queries)] q_codes: Option<*mut i8>,
- #[optional(quantize_queries)] q_scales: Option<*mut ElementT>,
- #[optional(append_kv)] k_codes: Option<*mut i8>,
- #[optional(append_kv)] k_scales: Option<*mut ElementT>,
- #[optional(append_kv)] v_codes: Option<*mut u8>,
- #[optional(append_kv)] v_scales: Option<*mut ElementT>,
- #[optional(has_rope)] cosines: Option<*const RopeT>,
- #[optional(has_rope)] sines: Option<*const RopeT>,
- num_q_heads: u32,
- #[optional(has_rope)] rope_dim: Option<u32>,
- kv_token_offset: u32,
- input_row_stride: u32,
- suffix_length: u32,
- query_rows: u32,
- #[specialize] has_rope: bool,
- #[specialize] quantize_queries: bool,
- #[specialize] num_kv_heads: u32,
- #[specialize] append_kv: bool,
-) {
- let head_dim = HEAD_DIM as usize;
- let rope_dim = if has_rope {
- rope_dim.unwrap() as usize
- } else {
- 0
- };
- let layout = Int8KVLayout::new(HEAD_DIM, num_kv_heads);
- let mut values = vec![0.0f32; head_dim];
- let gqa_factor = num_q_heads / num_kv_heads;
- let v_head_start = num_q_heads + num_kv_heads;
- for head in 0..v_head_start + num_kv_heads {
- let is_query = head < num_q_heads;
- if !append_kv && !is_query {
- continue;
- }
- let is_key = !is_query && head < v_head_start;
- let quantize = !is_query || quantize_queries;
- let (kv_head, scales) = match (is_query, is_key) {
- (true, _) => (0, q_scales),
- (_, true) => (head - num_q_heads, k_scales),
- _ => (head - v_head_start, v_scales),
- };
- for token in 0..suffix_length {
- let source = unsafe { qkvg.add((token * input_row_stride + head * HEAD_DIM) as usize) };
- for (channel, value) in values.iter_mut().enumerate() {
- let element = if (is_query || is_key) && channel < rope_dim {
- apply_rope(source, cosines.unwrap(), sines.unwrap(), token as usize, channel, rope_dim)
- } else {
- unsafe { *source.add(channel) }
- }
- .to_f32()
- .unwrap();
- if !quantize {
- let row = (head * suffix_length + token) as usize * head_dim;
- unsafe { *queries.unwrap().add(row + channel) = ElementT::from(element).unwrap() };
- } else {
- let sign_word = kv_layout::ROTATION_SIGN_BITS[channel / kv_layout::WORD_BITS as usize];
- let flip_sign = (sign_word >> (channel % kv_layout::WORD_BITS as usize)) & 1 != 0;
- *value = if flip_sign {
- -element
- } else {
- element
- };
- }
- }
- if !quantize {
- continue;
- }
- hadamard_transform(&mut values);
- let maximum = values.iter().fold(0.0f32, |maximum, value| maximum.max(value.abs()));
- let scale = ElementT::from(if maximum > 0.0 {
- maximum / INT8_MAX
- } else {
- 1.0
- })
- .unwrap();
- let scale_index = if is_query {
- ((head / gqa_factor) * query_rows + (head % gqa_factor) * suffix_length + token) as usize
- } else {
- layout.scale_index(kv_token_offset + token, kv_head)
- };
- for (channel, &value) in values.iter().enumerate() {
- let code = (value / scale.to_f32().unwrap()).round_ties_even().clamp(-INT8_MAX, INT8_MAX) as i8;
- unsafe {
- if is_query {
- *q_codes.unwrap().add(scale_index * head_dim + channel) = code;
- } else if is_key {
- *k_codes.unwrap().add(layout.k_code_index(kv_token_offset + token, kv_head, channel as u32)) =
- code;
- } else {
- *v_codes.unwrap().add(layout.v_code_index(kv_token_offset + token, kv_head, channel as u32)) =
- (i16::from(code) + kv_layout::V_CODE_BIAS) as u8;
- }
- }
- }
- unsafe { *scales.unwrap().add(scale_index) = scale };
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs
deleted file mode 100644
index 8425198ad..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::data_type::DataTypeRepr;
-
-#[kernel(QKVNorm)]
-#[variants(InputT, f32, bf16)]
-#[variants(ScaleT, f32, bf16)]
-#[variants(OutputT, f32, bf16)]
-#[variants(AccumT, f32)]
-pub fn qkv_norm<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float,
- AccumT: DataTypeRepr + Float,
->(
- #[optional(!in_place)] qkvg_input: Option<*const InputT>,
- #[optional(has_scales)] scales: Option<*const ScaleT>,
- qkvg_output: *mut OutputT,
- batch_size: u32,
- input_row_stride: u32,
- head_dim: u32,
- epsilon: f32,
- scale_offset: f32,
- head_offset: u32,
- head_count: u32,
- full_layer: bool,
- #[specialize] in_place: bool,
- #[specialize] has_scales: bool,
-) {
- let qkvg_input = match in_place {
- true => qkvg_output as *const InputT,
- false => qkvg_input.unwrap(),
- };
-
- let head_dim = head_dim as usize;
- let head_offset = head_offset as usize;
- let head_count = head_count as usize;
- let input_row_stride = input_row_stride as usize;
- let head_dim_accum = AccumT::from(head_dim).unwrap();
- let epsilon = AccumT::from(epsilon).unwrap();
- let scale_offset = AccumT::from(scale_offset).unwrap();
-
- for batch in 0..(batch_size as usize) {
- for head in 0..head_count {
- let offset = batch * input_row_stride + (head_offset + head) * head_dim;
-
- let mut total_sum = AccumT::zero();
- for i in 0..head_dim {
- let input_val = unsafe { AccumT::from(*qkvg_input.add(offset + i)).unwrap() };
- total_sum = total_sum + input_val * input_val;
- }
- let mean_square: AccumT = total_sum / head_dim_accum;
- let rms_norm = AccumT::from((mean_square + epsilon).to_f32().unwrap().sqrt().recip()).unwrap();
-
- for i in 0..head_dim {
- let input_val = unsafe { AccumT::from(*qkvg_input.add(offset + i)).unwrap() };
- let normalized: AccumT = input_val * rms_norm;
- let result: OutputT = if !has_scales {
- OutputT::from(normalized).unwrap()
- } else {
- let scale_val = unsafe { AccumT::from(*scales.unwrap().add(i)).unwrap() };
- if full_layer {
- let scale_with_offset: AccumT = scale_val + scale_offset;
- OutputT::from(normalized * scale_with_offset).unwrap()
- } else {
- let normalized_low = OutputT::from(normalized).unwrap();
- let scale_value_low = OutputT::from(scale_val + scale_offset).unwrap();
- normalized_low * scale_value_low
- }
- };
- unsafe { *qkvg_output.add(offset + i) = result };
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/rope.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/rope.rs
new file mode 100644
index 000000000..d9b9dd8b8
--- /dev/null
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/rope.rs
@@ -0,0 +1,30 @@
+use num_traits::Float;
+
+use crate::data_type::DataTypeRepr;
+
+pub(super) fn apply_rope<ElementT: DataTypeRepr + Float>(
+ head: *const ElementT,
+ cosines: *const (impl DataTypeRepr + Float),
+ sines: *const (impl DataTypeRepr + Float),
+ batch_idx: usize,
+ head_dim_idx: usize,
+ rope_dim: usize,
+) -> ElementT {
+ let half_rope_dim = rope_dim / 2;
+ let paired_idx = if head_dim_idx < half_rope_dim {
+ head_dim_idx + half_rope_dim
+ } else {
+ head_dim_idx - half_rope_dim
+ };
+ let input = unsafe { (*head.add(head_dim_idx)).to_f32().unwrap() };
+ let paired = unsafe { (*head.add(paired_idx)).to_f32().unwrap() };
+ let signed_paired = if head_dim_idx < half_rope_dim {
+ -paired
+ } else {
+ paired
+ };
+ let cos_val = unsafe { (*cosines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
+ let sin_val = unsafe { (*sines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
+
+ ElementT::from(input * cos_val + signed_paired * sin_val).unwrap()
+}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs
deleted file mode 100644
index c0cf351d3..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::data_type::DataTypeRepr;
-
-#[kernel(SigmoidGate)]
-#[variants(T, f32, bf16)]
-pub fn sigmoid_gate<T: DataTypeRepr + Float>(
- gate: *const T,
- output: *mut T,
- gate_dim: u32,
- batch_dim: u32,
- gate_row_stride: u32,
-) {
- assert!(gate_dim > 0, "sigmoid gate requires nonzero gate_dim");
- assert!(gate_row_stride >= gate_dim, "sigmoid gate row stride is too small");
- let gate_dim = gate_dim as usize;
- let batch_dim = batch_dim as usize;
- let gate_row_stride = gate_row_stride as usize;
- for batch_idx in 0..batch_dim {
- for gate_idx in 0..gate_dim {
- let output_idx = batch_idx * gate_dim + gate_idx;
- let gate_idx = batch_idx * gate_row_stride + gate_idx;
- let g = unsafe { (*gate.add(gate_idx)).to_f32().unwrap() };
- let sigmoid = 1.0f32 / (1.0f32 + (-g).exp());
- let out = unsafe { (*output.add(output_idx)).to_f32().unwrap() };
- unsafe { *output.add(output_idx) = T::from(out * sigmoid).unwrap() };
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/gpu_types/attention.rs b/crates/uzu-engine/src/backends/metal/gpu_types/attention.rs
index e0b648ead..32a2765b2 100644
--- a/crates/uzu-engine/src/backends/metal/gpu_types/attention.rs
+++ b/crates/uzu-engine/src/backends/metal/gpu_types/attention.rs
@@ -23,14 +23,6 @@ pub struct AttnParams {
/// Absolute offset of the first query token in the full key sequence.
/// For LLM decode/prefill this is the segment prefix length.
pub q_off: u32,
- /// Query tiling: q_len / BQ
- pub nq_aligned: u32,
- /// Query tiling: q_len % BQ
- pub q_rem: u32,
/// Key tiling: ceil(k_len / BK)
pub nk: u32,
- /// Key tiling: k_len / BK
- pub nk_aligned: u32,
- /// Key tiling: k_len % BK
- pub k_rem: u32,
}
diff --git a/crates/uzu-engine/src/backends/metal/gpu_types/kv_layout.rs b/crates/uzu-engine/src/backends/metal/gpu_types/kv_layout.rs
new file mode 100644
index 000000000..1d6cd7ffa
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/gpu_types/kv_layout.rs
@@ -0,0 +1,15 @@
+#[repr(C)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KVLayout {
+ RowMajor = 0,
+ MxuTiled = 1,
+}
+
+pub const TILE_KEYS: u32 = 32;
+pub const TILE_QUERIES: u32 = 16;
+pub const TILE_DIMS: u32 = 16;
+pub const FRAGMENT_BYTES: u32 = TILE_KEYS * TILE_DIMS;
+pub const SLICE_DIMS: u32 = 64;
+pub const GROUP_ROWS: u32 = 8;
+pub const LANE_COLS: u32 = 4;
+pub const LANE_BYTES: u32 = TILE_KEYS / GROUP_ROWS * LANE_COLS;
diff --git a/crates/uzu-engine/src/backends/metal/gpu_types/mod.rs b/crates/uzu-engine/src/backends/metal/gpu_types/mod.rs
index 4f0947a4e..db9619331 100644
--- a/crates/uzu-engine/src/backends/metal/gpu_types/mod.rs
+++ b/crates/uzu-engine/src/backends/metal/gpu_types/mod.rs
@@ -2,5 +2,6 @@
pub mod attention;
pub mod gemm;
+pub mod kv_layout;
pub mod matmul;
pub mod weaver;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/ancestor_attention.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/ancestor_attention.metal
index 2900c14b7..3014aa51a 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/ancestor_attention.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/ancestor_attention.metal
@@ -1,60 +1,29 @@
-#include <metal_simdgroup>
#include <metal_stdlib>
#include "../common/defines.h"
-#include "../common/integral_constant.h"
#include "../common/dsl.h"
#include "../common/thread_context.h"
+#include "../hadamard_transform/hadamard_transform.h"
#include "../weaver/weaver_frontier.h"
+#include "int8_quantization.h"
+#include "kv_layout.h"
+#include "rope.h"
using namespace metal;
#define SIMD_GROUPS_PER_THREADGROUP 4
#define THREADS_PER_THREADGROUP (SIMD_GROUPS_PER_THREADGROUP * METAL_SIMD_SIZE)
-constant uint VALUES_PER_VECTOR = 4;
-constant uint QKV_COMPONENTS = 3;
-constant uint KEY_COMPONENT = 1;
-constant uint VALUE_COMPONENT = 2;
-
-template <ushort UNROLL_COUNT, typename GetPtrBaseFn>
-METAL_FUNC void attend_qkv(
- float4 query,
- uint key_offset,
- uint value_offset,
- thread float4& values,
- thread float& max_score,
- thread float& sum,
- GetPtrBaseFn get_ptr_base
-) {
- float4 keys[UNROLL_COUNT];
- float4 position_values[UNROLL_COUNT];
- uzu::const_for_loop<0, UNROLL_COUNT, 1>([&](auto position) {
- const device bfloat4* vectors = get_ptr_base(position);
- keys[position] = float4(vectors[key_offset]);
- position_values[position] = float4(vectors[value_offset]);
- });
- float scores[UNROLL_COUNT];
- uzu::const_for_loop<0, UNROLL_COUNT, 1>([&](auto position) {
- scores[position] = simd_sum(dot(query, keys[position]));
- });
- float new_max = max_score;
- uzu::const_for_loop<0, UNROLL_COUNT, 1>([&](auto position) { new_max = max(new_max, scores[position]); });
- const float old_factor = fast::exp(max_score - new_max);
- sum *= old_factor;
- values *= old_factor;
- uzu::const_for_loop<0, UNROLL_COUNT, 1>([&](auto position) {
- const float factor = fast::exp(scores[position] - new_max);
- sum += factor;
- values += factor * position_values[position];
- });
- max_score = new_max;
-}
-
template <uint HEAD_DIM>
VARIANTS(HEAD_DIM, 128)
PUBLIC KERNEL(AncestorAttention)(
- const device bfloat* prefix_kv,
- device bfloat* node_kv,
+ const device int8_t* prefix_k_codes,
+ const device bfloat* prefix_k_scales,
+ const device uchar* prefix_v_codes,
+ const device bfloat* prefix_v_scales,
+ device int8_t* node_k_codes,
+ device bfloat* node_k_scales,
+ device uchar* node_v_codes,
+ device bfloat* node_v_scales,
const device bfloat* current_qkv,
const device float* cosines,
const device float* sines,
@@ -70,101 +39,95 @@ PUBLIC KERNEL(AncestorAttention)(
constant uint& max_depth,
constant float& scale,
const uint num_heads SPECIALIZE,
+ const uint32_t backend_opaque_layout SPECIALIZE,
const ThreadContext thread_context,
const uint group GROUPS((rows * num_heads).div_ceil(SIMD_GROUPS_PER_THREADGROUP)),
const uint lid THREADS(THREADS_PER_THREADGROUP)
) {
const uint row_head = group * SIMD_GROUPS_PER_THREADGROUP + thread_context.simdgroup_index;
- if (row_head >= rows * num_heads) {
+ if (row_head >= rows * num_heads)
return;
- }
-
- constexpr uint vectors_per_head = HEAD_DIM / VALUES_PER_VECTOR;
- constexpr ushort unroll_count = 4;
+ constexpr ushort N = HEAD_DIM / METAL_SIMD_SIZE;
const uint row = row_head / num_heads;
const uint head = row_head % num_heads;
- const uint lane = thread_context.simd_lane_id;
- const uint model_vectors = num_heads * vectors_per_head;
- const uint qkv_vectors = QKV_COMPONENTS * num_heads * vectors_per_head;
- const uint head_offset = head * vectors_per_head + lane;
- const uint current_key_offset = KEY_COMPONENT * model_vectors + head_offset;
- const uint current_value_offset = VALUE_COMPONENT * model_vectors + head_offset;
- const uint prefix_value_offset = prefix_length * model_vectors + head_offset;
- const uint node_value_offset = node_capacity * model_vectors + head_offset;
- const device bfloat4* prefix_vectors = (const device bfloat4*)prefix_kv;
- device bfloat4* node_vectors = (device bfloat4*)node_kv;
- const device bfloat4* current_row = (const device bfloat4*)current_qkv + row * qkv_vectors;
-
- // 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 = depth + 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])));
- float4 values = float4(prefix_vectors[prefix_value_offset]);
- float sum = 1.0f;
-
- uint position = 1;
- for (; position + unroll_count - 1 < prefix_length; position += unroll_count) {
- attend_qkv<unroll_count>(query, head_offset, prefix_value_offset, values, max_score, sum, [&](int step) {
- return prefix_vectors + (position + step) * model_vectors;
- });
- }
- for (; position < prefix_length; ++position) {
- attend_qkv<1>(query, head_offset, prefix_value_offset, values, max_score, sum, [&](int) {
- return prefix_vectors + position * model_vectors;
- });
- }
-
- const uint ancestor_count = ancestor_counts[row];
- const device uint* row_ancestors = ancestor_indices + row * ancestor_stride;
- uint offset = 0;
- for (; offset + unroll_count - 1 < ancestor_count; offset += unroll_count) {
- attend_qkv<unroll_count>(query, head_offset, node_value_offset, values, max_score, sum, [&](int step) {
- return node_vectors + row_ancestors[offset + step] * model_vectors;
- });
+ const ushort lane = ushort(thread_context.simd_lane_id);
+ const uint model_dim = num_heads * HEAD_DIM;
+ const uint position = node_metadata[uint(MetadataIdx::Depth) * rows + row] + 1;
+ const device bfloat* qkv = current_qkv + row * 3 * model_dim + head * HEAD_DIM;
+ const uzu::kv_layout::KVShape shape{
+ HEAD_DIM,
+ num_heads,
+ static_cast<uzu::kv_layout::KVLayout>(backend_opaque_layout)
+ };
+ float query[N], key[N], value[N];
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ const float sign = uzu::kv_layout::rotation_sign(channel);
+ query[i] = float(apply_rope(qkv, cosines, sines, position, channel, HEAD_DIM)) * sign;
+ key[i] = float(apply_rope(qkv + model_dim, cosines, sines, position, channel, HEAD_DIM)) * sign;
+ value[i] = float(qkv[2 * model_dim + channel]) * sign;
}
- for (; offset < ancestor_count; ++offset) {
- attend_qkv<1>(query, head_offset, node_value_offset, values, max_score, sum, [&](int) {
- return node_vectors + row_ancestors[offset] * model_vectors;
- });
+ simdgroup_hadamard_transform<N, METAL_SIMD_SIZE>(lane, query);
+ simdgroup_hadamard_transform<N, METAL_SIMD_SIZE>(lane, key);
+ simdgroup_hadamard_transform<N, METAL_SIMD_SIZE>(lane, value);
+ int q[N], k[N], v[N];
+ const float qs = float(kv_quantize_row<N>(query, q));
+ const bfloat ks = kv_quantize_row<N>(key, k);
+ const bfloat vs = kv_quantize_row<N>(value, v);
+ float result[N] = {};
+ float maximum = -INFINITY;
+ float denominator = 0.0f;
+ const uint ancestors = ancestor_counts[row];
+ for (uint index = 0; index < prefix_length + ancestors + 1; ++index) {
+ const bool own = index == prefix_length + ancestors;
+ const bool prefix = index < prefix_length;
+ const uint slot = prefix || own ? index : ancestor_indices[row * ancestor_stride + index - prefix_length];
+ const device int8_t* kc = prefix ? prefix_k_codes : node_k_codes;
+ const device uchar* vc = prefix ? prefix_v_codes : node_v_codes;
+ const float key_scale =
+ own ? float(ks) : float((prefix ? prefix_k_scales : node_k_scales)[shape.scale_index(slot, head)]);
+ const float value_scale =
+ own ? float(vs) : float((prefix ? prefix_v_scales : node_v_scales)[shape.scale_index(slot, head)]);
+ int dot = 0;
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ dot += q[i] * (own ? k[i] : int(kc[shape.k_code_index(slot, head, channel)]));
+ }
+ const float score = float(simd_sum(dot)) * qs * key_scale * scale;
+ const float next_max = max(maximum, score);
+ const float correction = fast::exp(maximum - next_max);
+ const float probability = fast::exp(score - next_max);
+ denominator = denominator * correction + probability;
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ const int code = own ? v[i] : int(vc[shape.v_code_index(slot, head, channel)]) - 128;
+ result[i] = result[i] * correction + probability * value_scale * float(code);
+ }
+ maximum = next_max;
}
-
- 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) {
+ if (node_capacity > 0) {
const uint node = node_indices[row];
-
- node_vectors[node * model_vectors + head_offset] = bfloat4(rotated_key);
- node_vectors[node_value_offset + node * model_vectors] = current_row[current_value_offset];
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ node_k_codes[shape.k_code_index(node, head, channel)] = int8_t(k[i]);
+ node_v_codes[shape.v_code_index(node, head, channel)] = uchar(v[i] + 128);
+ }
+ if (lane == 0) {
+ node_k_scales[shape.scale_index(node, head)] = ks;
+ node_v_scales[shape.scale_index(node, head)] = vs;
+ }
+ }
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i)
+ result[i] /= denominator;
+ simdgroup_hadamard_transform<N, METAL_SIMD_SIZE>(lane, result);
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < N; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ output[row_head * HEAD_DIM + channel] = bfloat(result[i] * uzu::kv_layout::rotation_sign(channel));
}
-
- ((device bfloat4*)output)[(row * num_heads + head) * vectors_per_head + lane] = bfloat4(values / sum);
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal
deleted file mode 100644
index 23a3dc938..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal
+++ /dev/null
@@ -1,343 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../matmul/common/fragment.h"
-#include "../matmul/common/loader.h"
-#include "../matmul/common/mxu_fragment/ops.h"
-#include "../matmul/common/simdgroup_fragment_ops.h"
-#include "../generated/ring.h"
-#include "../generated/trie.h"
-#include "../generated/attention.h"
-#include "mask.h"
-
-using namespace metal;
-using namespace uzu::matmul;
-using namespace uzu::attention;
-using namespace uzu::ring;
-using namespace uzu::trie;
-
-template <typename T>
-struct TransformScale {
- T scale;
- METAL_FUNC TransformScale(T scale_) : scale(scale_) {}
- METAL_FUNC T apply(T x) const { return scale * x; }
-};
-
-template <typename T, uint BK, uint BD, bool USE_MXU>
-struct AttentionGemmLayout {
- using Ops = metal::conditional_t<USE_MXU, MxuFragmentOps<>, SimdgroupFragmentOps>;
-
- UZU_CONST int FRAGMENT_ROWS = Ops::FRAGMENT_ROWS;
- UZU_CONST int SIMDGROUPS_PER_THREADGROUP = 4;
- UZU_CONST int BLOCK_QUERY_ROWS = SIMDGROUPS_PER_THREADGROUP * FRAGMENT_ROWS;
- UZU_CONST int ROW_ALIGNMENT_BYTES = 16;
- UZU_CONST int ROW_PADDING_ELEMENTS = ROW_ALIGNMENT_BYTES / int(sizeof(T));
- UZU_CONST int Q_SMEM_SIZE = USE_MXU ? 1 : (BLOCK_QUERY_ROWS * (int(BD) + ROW_PADDING_ELEMENTS));
- UZU_CONST int KV_SMEM_SIZE = USE_MXU ? 1 : (int(BK) * (int(BD) + ROW_PADDING_ELEMENTS));
-};
-
-template <typename T, uint BK, uint BD, bool USE_MXU>
-VARIANTS(T, bfloat)
-VARIANTS(BK, 16, 32)
-VARIANTS(BD, 64, 128, 256)
-VARIANTS(USE_MXU, false, true)
-CONSTRAINT(!USE_MXU || BK == 32)
-CONSTRAINT(!USE_MXU || BD != 256)
-KERNEL(AttentionGemm)(
- const device T* q,
- const device T* k,
- const device T* v,
- device T* o,
- const constant AttnParams& params,
- const constant RingParams& ring_params OPTIONAL(is_kv_cache_ring),
- const device TrieNode* trie OPTIONAL(is_trie),
- const constant uint& sliding_window_size OPTIONAL(is_sliding_window),
- const device T* sinks OPTIONAL(has_sinks),
- const constant uint& num_heads,
- const constant uint& suffix_length,
- const bool align_q SPECIALIZE,
- const bool align_k SPECIALIZE,
- const bool is_kv_cache_ring SPECIALIZE,
- const bool is_causal SPECIALIZE,
- const bool is_trie SPECIALIZE,
- const bool is_sliding_window SPECIALIZE,
- const bool has_sinks SPECIALIZE,
- threadgroup T q_smem[AttentionGemmLayout<T, BK, BD, USE_MXU>::Q_SMEM_SIZE],
- threadgroup T kv_smem[AttentionGemmLayout<T, BK, BD, USE_MXU>::KV_SMEM_SIZE],
- const ThreadContext thread_context,
- const uint q_tile_idx GROUPS(suffix_length.div_ceil(if USE_MXU { 64 } else { 32 })),
- const uint head_idx GROUPS(num_heads),
- const uint batch_idx GROUPS(1),
- const uint lid THREADS(128)
-) {
- using AccumType = float;
- using Layout = AttentionGemmLayout<T, BK, BD, USE_MXU>;
- using Ops = typename Layout::Ops;
- constexpr short FRAGMENT_ROWS = Layout::FRAGMENT_ROWS;
- constexpr int BLOCK_QUERY_ROWS = Layout::BLOCK_QUERY_ROWS;
- constexpr int ROW_PADDING_ELEMENTS = Layout::ROW_PADDING_ELEMENTS;
- constexpr int SIMDGROUPS_PER_THREADGROUP = Layout::SIMDGROUPS_PER_THREADGROUP;
- constexpr bool QUERY_IS_RESIDENT = USE_MXU;
-
- using InputType = metal::conditional_t<USE_MXU, T, AccumType>;
-
- q += batch_idx * uint64_t(params.q_strides[0]) + head_idx * uint64_t(params.q_strides[1]) +
- q_tile_idx * int64_t(BLOCK_QUERY_ROWS) * params.q_strides[2];
-
- const int kv_head_idx = int(head_idx) / params.gqa_factor;
- k += batch_idx * uint64_t(params.k_strides[0]) + int64_t(kv_head_idx) * params.k_strides[1];
- v += batch_idx * uint64_t(params.v_strides[0]) + int64_t(kv_head_idx) * params.v_strides[1];
-
- o += batch_idx * uint64_t(params.o_strides[0]) + head_idx * uint64_t(params.o_strides[1]) +
- q_tile_idx * int64_t(BLOCK_QUERY_ROWS) * params.o_strides[2];
-
- if (is_trie) {
- trie += batch_idx * suffix_length;
- }
-
- const int query_source_stride = int(params.q_strides[2]);
- const int key_source_stride = int(params.k_strides[2]);
- const int value_source_stride = int(params.v_strides[2]);
-
- constexpr int QUERY_ROW_FRAGMENTS = 1;
- constexpr int KEY_COL_FRAGMENTS = BK / FRAGMENT_ROWS;
- constexpr int HEAD_DIM_FRAGMENTS = BD / FRAGMENT_ROWS;
-
- static_assert(!USE_MXU || KEY_COL_FRAGMENTS % 2 == 0, "MXU QK needs even N (KEY_COL_FRAGMENTS)");
-
- constexpr int QUERY_FRAGMENT_COUNT = QUERY_IS_RESIDENT ? HEAD_DIM_FRAGMENTS : 1;
- using QueryFragment = OperandFragment<InputType, QUERY_ROW_FRAGMENTS, 1, Ops>;
- using KeyFragment = OperandFragment<InputType, 1, KEY_COL_FRAGMENTS, Ops, ReadTranspose>;
- using ScoreFragment = Fragment<AccumType, QUERY_ROW_FRAGMENTS, KEY_COL_FRAGMENTS, Ops>;
- QueryFragment query_frags[QUERY_FRAGMENT_COUNT];
- ScoreFragment score_fragment;
- constexpr int VALUE_COL_FRAGMENTS = USE_MXU ? 2 : (HEAD_DIM_FRAGMENTS < 16 ? HEAD_DIM_FRAGMENTS : 16);
- static_assert(HEAD_DIM_FRAGMENTS % VALUE_COL_FRAGMENTS == 0, "head-dim must split into VALUE_COL_FRAGMENTS frags");
- static_assert(!USE_MXU || VALUE_COL_FRAGMENTS % 2 == 0, "MXU PV needs even N (VALUE_COL_FRAGMENTS)");
- constexpr int OUTPUT_CHUNKS = HEAD_DIM_FRAGMENTS / VALUE_COL_FRAGMENTS;
- constexpr short OUTPUT_CHUNK_COLS = VALUE_COL_FRAGMENTS * FRAGMENT_ROWS;
- using ValueFragment = OperandFragment<InputType, KEY_COL_FRAGMENTS, VALUE_COL_FRAGMENTS, Ops>;
- using OutputFragment = Fragment<AccumType, QUERY_ROW_FRAGMENTS, VALUE_COL_FRAGMENTS, Ops>;
- OutputFragment output_chunks[OUTPUT_CHUNKS];
-
- METAL_PRAGMA_UNROLL
- for (int c = 0; c < OUTPUT_CHUNKS; ++c) {
- output_chunks[c].clear();
- }
-
- const short simdgroup_row_base = FRAGMENT_ROWS * QUERY_ROW_FRAGMENTS * short(thread_context.simdgroup_index);
- constexpr short head_dim_fragment_stride = FRAGMENT_ROWS;
-
- const bool ragged_q = (!align_q && q_tile_idx == params.nq_aligned);
- constexpr short query_leading_dimension = BD + ROW_PADDING_ELEMENTS;
- threadgroup T* query_shared = q_smem;
- const short query_shared_offset = simdgroup_row_base * query_leading_dimension;
-
- if constexpr (QUERY_IS_RESIDENT) {
- auto q_src = fragment_source(q + int64_t(simdgroup_row_base) * query_source_stride, query_source_stride);
- if (ragged_q) {
- q_src = q_src.bounded(params.q_rem - simdgroup_row_base, FRAGMENT_ROWS);
- }
- const InputType query_scale = static_cast<InputType>(params.scale * M_LOG2E_F);
- METAL_PRAGMA_UNROLL
- for (short dd = 0; dd < HEAD_DIM_FRAGMENTS; dd++) {
- query_frags[dd].load_from(thread_context.simd_lane_id, q_src.advanced(dd * head_dim_fragment_stride));
- query_frags[dd].map_coords(thread_context.simd_lane_id, [&](short, short, InputType v) {
- return v * query_scale;
- });
- }
- } else {
- using QueryLoader = ThreadgroupLoader<
- T,
- BLOCK_QUERY_ROWS,
- BD,
- query_leading_dimension,
- 1,
- SIMDGROUPS_PER_THREADGROUP * METAL_SIMD_SIZE>;
- thread QueryLoader query_loader(q, query_source_stride, query_shared, thread_context);
- if (ragged_q) {
- query_loader.load_safe(short2(BD, params.q_rem));
- } else {
- query_loader.load_unsafe();
- }
- query_loader.apply_inplace_op(::TransformScale<T>(static_cast<T>(params.scale * M_LOG2E_F)));
- threadgroup_barrier(mem_flags::mem_threadgroup);
- }
-
- const AccumType masked_score = static_cast<AccumType>(-1e9f) * M_LOG2E_F;
- constexpr int ROWS_PER_LANE = QUERY_ROW_FRAGMENTS * Ops::THREAD_ELEMENT_ROWS;
- const AccumType init_max = has_sinks ? AccumType(M_LOG2E_F * static_cast<AccumType>(sinks[head_idx])) : -INFINITY;
- const AccumType init_sum = has_sinks ? AccumType(1) : AccumType(0);
- AccumType max_score[ROWS_PER_LANE];
- AccumType sum_score[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- max_score[r] = init_max;
- sum_score[r] = init_sum;
- }
-
- int kb_lim = int(params.nk);
- if (is_causal) {
- const int q_max = (int(q_tile_idx) + 1) * BLOCK_QUERY_ROWS + params.q_off;
- kb_lim = min(int(params.nk), (q_max + int(BK) - 1) / int(BK));
- }
-
- const int q_base = int(q_tile_idx) * BLOCK_QUERY_ROWS + int(simdgroup_row_base);
- const int prefix_length = params.q_off;
- const int suffix_position = is_kv_cache_ring ? int(ring_params.ring_length) : prefix_length;
- using KVBlockSource = BlockSource<
- T,
- BK,
- BD,
- BD + ROW_PADDING_ELEMENTS,
- SIMDGROUPS_PER_THREADGROUP * METAL_SIMD_SIZE,
- typename Ops::BlockStorage>;
- threadgroup T* kv_shared = kv_smem;
-
- for (int kb = 0; kb < kb_lim; kb++) {
- const bool tail_k = (!align_k && kb == int(params.nk_aligned));
- const short valid_k_rows = tail_k ? short(params.k_rem) : short(BK);
- const device T* k_block = k + int64_t(kb) * int(BK) * key_source_stride;
- score_fragment.clear();
-
- KVBlockSource key_source{
- k_block,
- key_source_stride,
- kv_shared,
- valid_k_rows,
- thread_context,
- };
- key_source.prepare();
- auto q_shared_src = fragment_source(query_shared + query_shared_offset, query_leading_dimension);
-
- METAL_PRAGMA_UNROLL
- for (short dd = 0; dd < HEAD_DIM_FRAGMENTS; dd++) {
- if constexpr (!QUERY_IS_RESIDENT) {
- query_frags[0].load_from(thread_context.simd_lane_id, q_shared_src.advanced(dd * head_dim_fragment_stride));
- }
- const short q_idx = QUERY_IS_RESIDENT ? dd : 0;
-
- KeyFragment key_fragment;
- key_source.load(key_fragment, dd * head_dim_fragment_stride);
- simdgroup_barrier(mem_flags::mem_none);
- fragment_mma(score_fragment, query_frags[q_idx], key_fragment);
- }
-
- const int k_rem = params.k_rem;
- if (!is_trie && !is_kv_cache_ring && !is_sliding_window) {
- const bool diag = is_causal && ((int(kb) + 1) * int(BK) - 1 > prefix_length + q_base);
- if (tail_k || diag) {
- score_fragment.map_coords(thread_context.simd_lane_id, [&](short row, short col, AccumType v) {
- if (tail_k && int(col) >= k_rem) {
- return masked_score;
- }
- if (diag && (kb * int(BK) + int(col)) > prefix_length + q_base + int(row)) {
- return masked_score;
- }
- return v;
- });
- }
- } else {
- score_fragment.map_coords(thread_context.simd_lane_id, [&](short row, short col, AccumType v) {
- if (tail_k && int(col) >= k_rem) {
- return masked_score;
- }
- const int q_rel = q_base + int(row);
- if (q_rel >= int(params.q_len)) {
- return v;
- }
- const int key = kb * BK + int(col);
- if (key >= int(params.k_len)) {
- return v;
- }
- const int query_position = is_trie ? suffix_position + int(trie[q_rel].height) : suffix_position + q_rel;
- if (!should_use_key(
- ring_params,
- trie,
- sliding_window_size,
- q_rel,
- prefix_length,
- suffix_position,
- query_position,
- key,
- is_kv_cache_ring,
- is_causal,
- is_trie,
- is_sliding_window
- )) {
- return masked_score;
- }
- return v;
- });
- }
-
- AccumType block_max[ROWS_PER_LANE];
- score_fragment.row_reduce(block_max, -INFINITY, [](AccumType a, AccumType b) { return metal::max(a, b); });
-
- AccumType new_max[ROWS_PER_LANE];
- AccumType factor[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- new_max[r] = metal::max(max_score[r], block_max[r]);
- factor[r] = fast::exp2(max_score[r] - new_max[r]);
- max_score[r] = new_max[r];
- sum_score[r] *= factor[r];
- }
-
- score_fragment.map_rows(new_max, [](AccumType v, AccumType m) { return fast::exp2(v - m); });
-
- AccumType block_sum[ROWS_PER_LANE];
- score_fragment.row_reduce(block_sum, AccumType(0), [](AccumType a, AccumType b) { return a + b; });
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- sum_score[r] += block_sum[r];
- }
-
- METAL_PRAGMA_UNROLL
- for (int c = 0; c < OUTPUT_CHUNKS; ++c) {
- output_chunks[c].map_rows(factor, [](AccumType v, AccumType f) { return v * f; });
- }
-
- const device T* v_block = v + int64_t(kb) * int(BK) * value_source_stride;
- KVBlockSource value_source{
- v_block,
- value_source_stride,
- kv_shared,
- valid_k_rows,
- thread_context,
- };
- value_source.prepare();
- METAL_PRAGMA_UNROLL
- for (int c = 0; c < OUTPUT_CHUNKS; ++c) {
- ValueFragment value_chunk;
- value_source.load(value_chunk, c * OUTPUT_CHUNK_COLS);
- fragment_mma(output_chunks[c], score_fragment, value_chunk);
- }
- }
-
- AccumType inv_sum[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- inv_sum[r] = AccumType(1) / sum_score[r];
- }
- METAL_PRAGMA_UNROLL
- for (int c = 0; c < OUTPUT_CHUNKS; ++c) {
- output_chunks[c].map_rows(inv_sum, [](AccumType v, AccumType s) { return v * s; });
- }
-
- o += int64_t(simdgroup_row_base) * params.o_strides[2];
-
- if (ragged_q && int(params.q_rem) <= int(simdgroup_row_base)) {
- return;
- }
- METAL_PRAGMA_UNROLL
- for (int c = 0; c < OUTPUT_CHUNKS; ++c) {
- device T* o_chunk = o + c * OUTPUT_CHUNK_COLS;
- if (ragged_q) {
- const short2 dst_tile_dims = short2(OUTPUT_CHUNK_COLS, params.q_rem - simdgroup_row_base);
- output_chunks[c].store_safe(thread_context.simd_lane_id, o_chunk, int(params.o_strides[2]), dst_tile_dims);
- } else {
- output_chunks[c].store(thread_context.simd_lane_id, o_chunk, int(params.o_strides[2]));
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal
deleted file mode 100644
index aa20b7811..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal
+++ /dev/null
@@ -1,51 +0,0 @@
-#include "../common/dsl.h"
-#include "rope.h"
-
-template <typename ElementT, typename RopeT>
-VARIANTS(ElementT, bfloat)
-VARIANTS(RopeT, float)
-PUBLIC KERNEL(AttentionPrepare) (
- const device ElementT* qkvg, // [token, input_row_stride], with an optional trailing gate
- device ElementT* queries, // [head_idx, token, head_dim]
- device ElementT* keys OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]
- device ElementT* values OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]
- const device RopeT* cosines OPTIONAL(has_rope),
- const device RopeT* sines OPTIONAL(has_rope),
- const constant uint32_t& num_q_heads,
- const constant uint32_t& num_kv_heads OPTIONAL(has_kv),
- const constant uint32_t& head_dim,
- const constant uint32_t& rope_dim OPTIONAL(has_rope),
- const constant uint32_t& kv_token_offset OPTIONAL(has_kv),
- const constant uint32_t& input_row_stride,
- const constant uint32_t& batch_dim,
- const bool has_kv SPECIALIZE,
- const bool has_rope SPECIALIZE,
- const uint32_t head_dim_idx AXIS(head_dim, 128),
- const uint32_t head_idx AXIS(num_q_heads + num_kv_heads.unwrap_or(0) * 2, 1),
- const uint32_t batch_idx AXIS(batch_dim, 1)
-) {
- const uint32_t qkvg_head_idx = batch_idx * input_row_stride + head_idx * head_dim;
- const device ElementT* qkvg_head = qkvg + qkvg_head_idx;
- const bool is_query = !has_kv || head_idx < num_q_heads;
- const bool is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;
-
- ElementT element = qkvg_head[head_dim_idx];
- if (has_rope && head_dim_idx < rope_dim && (is_query || is_key)) {
- element = apply_rope(qkvg_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);
- }
-
- if (is_query) {
- const uint32_t q_idx = head_idx * batch_dim * head_dim + batch_idx * head_dim + head_dim_idx;
- queries[q_idx] = element;
- } else if (is_key) {
- const uint32_t k_idx =
- (kv_token_offset + batch_idx) * num_kv_heads * head_dim + (head_idx - num_q_heads) * head_dim + head_dim_idx;
-
- keys[k_idx] = element;
- } else if (has_kv) {
- const uint32_t v_idx = (kv_token_offset + batch_idx) * num_kv_heads * head_dim +
- (head_idx - num_q_heads - num_kv_heads) * head_dim + head_dim_idx;
-
- values[v_idx] = element;
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_single_pass.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_single_pass.metal
deleted file mode 100644
index 75651d57e..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_single_pass.metal
+++ /dev/null
@@ -1,173 +0,0 @@
-#include <metal_stdlib>
-#include <metal_simdgroup>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../generated/ring.h"
-#include "../generated/trie.h"
-#include "mask.h"
-
-#define SEQUENCE_BLOCK_SIZE 32
-#define HEAD_BLOCK_SIZE 32
-
-using namespace uzu::ring;
-using namespace uzu::trie;
-
-template <typename T, uint HEAD_DIM>
-VARIANTS(T, bfloat)
-VARIANTS(HEAD_DIM, 64, 128, 256, 512)
-PUBLIC KERNEL(AttentionSinglePass)(
- const device T* queries,
- const device T* keys,
- const device T* values,
- device T* out,
- const constant uint& gqa_factor,
- const constant uint& sequence_length,
- const constant uint& k_head_stride,
- const constant uint& k_seq_stride,
- const constant uint& v_head_stride,
- const constant uint& v_seq_stride,
- const constant RingParams& ring_params OPTIONAL(is_kv_cache_ring),
- const constant float& scale,
- const device TrieNode* trie OPTIONAL(is_trie),
- const constant uint& sliding_window_size OPTIONAL(is_sliding_window),
- const device T* sinks OPTIONAL(has_sinks),
- const constant uint& num_heads,
- const constant uint& suffix_length,
- threadgroup float shared_max_scores[SEQUENCE_BLOCK_SIZE * HEAD_BLOCK_SIZE],
- threadgroup float shared_sum_exp_scores[SEQUENCE_BLOCK_SIZE * HEAD_BLOCK_SIZE],
- threadgroup float shared_outputs[SEQUENCE_BLOCK_SIZE * HEAD_BLOCK_SIZE],
- const bool has_sinks SPECIALIZE,
- const bool is_kv_cache_ring SPECIALIZE,
- const bool is_causal SPECIALIZE,
- const bool is_trie SPECIALIZE,
- const bool is_sliding_window SPECIALIZE,
- const ThreadContext thread_context,
- const uint head_idx GROUPS(num_heads),
- const uint q_seq_idx GROUPS(suffix_length),
- const uint tid THREADS(1024)
-) {
- constexpr bool query_transposed = false;
-
- constexpr uint value_dim = HEAD_DIM;
- constexpr uint qk_elements_per_thread = HEAD_DIM / HEAD_BLOCK_SIZE;
- constexpr uint value_elements_per_thread = value_dim / HEAD_BLOCK_SIZE;
- uint inner_k_stride = SEQUENCE_BLOCK_SIZE * int(k_seq_stride);
- uint inner_v_stride = SEQUENCE_BLOCK_SIZE * int(v_seq_stride);
-
- typedef float U;
-
- thread U q[qk_elements_per_thread];
- thread U k[qk_elements_per_thread];
- thread U o[value_elements_per_thread];
-
- const uint kv_head_idx = head_idx / gqa_factor;
- const uint o_offset = q_seq_idx * num_heads + head_idx;
- const uint q_offset = query_transposed ? num_heads * q_seq_idx + head_idx : head_idx * suffix_length + q_seq_idx;
-
- const uint prefix_length = sequence_length - suffix_length;
-
- const uint suffix_position = is_kv_cache_ring ? uint(ring_params.ring_length) : prefix_length;
-
- const uint query_position = is_trie ? suffix_position + trie[q_seq_idx].height : suffix_position + q_seq_idx;
-
- queries += q_offset * HEAD_DIM + thread_context.simd_lane_id * qk_elements_per_thread;
- keys += kv_head_idx * k_head_stride + thread_context.simdgroup_index * k_seq_stride +
- thread_context.simd_lane_id * qk_elements_per_thread;
- values += kv_head_idx * v_head_stride + thread_context.simdgroup_index * v_seq_stride +
- thread_context.simd_lane_id * value_elements_per_thread;
-
- out += o_offset * value_dim + thread_context.simdgroup_index * value_elements_per_thread;
-
- // Read the query and 0 the output accumulator
- for (uint i = 0; i < qk_elements_per_thread; i++) {
- q[i] = static_cast<U>(scale) * queries[i];
- }
- for (uint i = 0; i < value_elements_per_thread; i++) {
- o[i] = 0;
- }
-
- U max_score = -INFINITY;
- U sum_exp_score = 0;
- if (has_sinks && thread_context.simdgroup_index == 0) {
- const int num_q_heads = static_cast<int>(num_heads);
- int q_head_idx = head_idx % num_q_heads;
- max_score = static_cast<U>(sinks[q_head_idx]);
- sum_exp_score = 1;
- }
-
- // For each key
- for (uint i = thread_context.simdgroup_index; i < sequence_length; i += SEQUENCE_BLOCK_SIZE) {
- if (should_use_key(
- ring_params,
- trie,
- sliding_window_size,
- q_seq_idx,
- prefix_length,
- suffix_position,
- query_position,
- i,
- is_kv_cache_ring,
- is_causal,
- is_trie,
- is_sliding_window
- )) {
- // Read the key
- for (uint j = 0; j < qk_elements_per_thread; j++) {
- k[j] = keys[j];
- }
-
- // Compute the i-th score
- U score = 0;
- for (uint j = 0; j < qk_elements_per_thread; j++) {
- score += q[j] * k[j];
- }
- score = simd_sum(score);
-
- // Update the accumulators
- U new_max = max(max_score, score);
- U factor = fast::exp(max_score - new_max);
- U exp_score = fast::exp(score - new_max);
-
- max_score = new_max;
- sum_exp_score = sum_exp_score * factor + exp_score;
-
- // Update the output accumulator
- for (uint j = 0; j < value_elements_per_thread; j++) {
- o[j] = o[j] * factor + exp_score * values[j];
- }
- }
-
- // Move the pointers to the next kv
- keys += inner_k_stride;
- values += inner_v_stride;
- }
-
- // Each thread has a partial part of the output so we need to combine them.
- if (thread_context.simd_lane_id == 0) {
- shared_max_scores[thread_context.simdgroup_index] = max_score;
- shared_sum_exp_scores[thread_context.simdgroup_index] = sum_exp_score;
- }
- threadgroup_barrier(mem_flags::mem_threadgroup);
- max_score = shared_max_scores[thread_context.simd_lane_id];
- U new_max = simd_max(max_score);
- U factor = fast::exp(max_score - new_max);
- sum_exp_score = simd_sum(shared_sum_exp_scores[thread_context.simd_lane_id] * factor);
-
- // Now we need to aggregate all the outputs
- for (uint i = 0; i < value_elements_per_thread; i++) {
- shared_outputs[thread_context.simd_lane_id * HEAD_BLOCK_SIZE + thread_context.simdgroup_index] = o[i];
- threadgroup_barrier(mem_flags::mem_threadgroup);
- o[i] = simd_sum(
- shared_outputs[thread_context.simdgroup_index * HEAD_BLOCK_SIZE + thread_context.simd_lane_id] * factor
- ) /
- sum_exp_score;
- threadgroup_barrier(mem_flags::mem_threadgroup);
- }
-
- // And write the output
- if (thread_context.simd_lane_id == 0) {
- for (uint i = 0; i < value_elements_per_thread; i++) {
- out[i] = static_cast<T>(o[i]);
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_two_pass.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_two_pass.metal
deleted file mode 100644
index e6e1e6643..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_two_pass.metal
+++ /dev/null
@@ -1,212 +0,0 @@
-#include <metal_stdlib>
-#include <metal_simdgroup>
-#include "../common/defines.h"
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../generated/ring.h"
-#include "../generated/trie.h"
-#include "../common/sigmoid_gate.h"
-#include "mask.h"
-
-#define TOTAL_BLOCKS_COUNT 32
-#define SIMDGROUPS_PER_THREADGROUP 8
-
-using namespace uzu::ring;
-using namespace uzu::trie;
-
-// GQA-aware two-pass attention (pass 1).
-// Fixed 256-thread threadgroups (8 simdgroups) with flat query-head mapping.
-// Each simdgroup independently handles one query head and derives its KV head
-// via integer division. Simdgroups sharing a KV head benefit from L1 cache.
-template <typename T, uint HEAD_DIM>
-VARIANTS(T, bfloat)
-VARIANTS(HEAD_DIM, 64, 128, 256, 512)
-KERNEL(AttentionTwoPass1)(
- const device T* queries,
- const device T* keys,
- const device T* values,
- device float* out,
- device float* sums,
- device float* maxs,
- const constant uint& gqa_factor,
- const constant uint& sequence_length,
- const constant uint& k_head_stride,
- const constant uint& k_seq_stride,
- const constant uint& v_head_stride,
- const constant uint& v_seq_stride,
- const constant RingParams& ring_params OPTIONAL(is_kv_cache_ring),
- const constant float& scale,
- const constant uint& num_heads,
- const constant uint& suffix_length,
- const device TrieNode* trie OPTIONAL(is_trie),
- const constant uint& sliding_window_size OPTIONAL(is_sliding_window),
- const device T* sinks OPTIONAL(has_sinks),
- const bool has_sinks SPECIALIZE,
- const bool is_kv_cache_ring SPECIALIZE,
- const bool is_causal SPECIALIZE,
- const bool is_trie SPECIALIZE,
- const bool is_sliding_window SPECIALIZE,
- const ThreadContext thread_context,
- const uint head_group_idx GROUPS(num_heads.div_ceil(SIMDGROUPS_PER_THREADGROUP)),
- const uint q_seq_idx GROUPS(suffix_length),
- const uint block_idx GROUPS(TOTAL_BLOCKS_COUNT),
- const uint tid THREADS(SIMDGROUPS_PER_THREADGROUP * METAL_SIMD_SIZE)
-) {
- constexpr uint elements_per_thread = HEAD_DIM / METAL_SIMD_SIZE;
-
- typedef float U;
-
- // Flat query head mapping — fixed hardware shape, dynamic logical mapping
- const uint head_idx = head_group_idx * SIMDGROUPS_PER_THREADGROUP + thread_context.simdgroup_index;
- if (head_idx >= num_heads)
- return;
-
- const uint kv_head_idx = head_idx / gqa_factor;
- const uint o_offset = q_seq_idx * num_heads + head_idx;
- const uint q_offset = head_idx * suffix_length + q_seq_idx;
-
- const uint prefix_length = sequence_length - suffix_length;
- const uint suffix_position = is_kv_cache_ring ? uint(ring_params.ring_length) : prefix_length;
- const uint query_position = is_trie ? suffix_position + trie[q_seq_idx].height : suffix_position + q_seq_idx;
-
- thread U q[elements_per_thread];
- thread U o[elements_per_thread] = {0};
-
- queries += q_offset * HEAD_DIM + thread_context.simd_lane_id * elements_per_thread;
- keys += kv_head_idx * k_head_stride + block_idx * k_seq_stride + thread_context.simd_lane_id * elements_per_thread;
- values += kv_head_idx * v_head_stride + block_idx * v_seq_stride + thread_context.simd_lane_id * elements_per_thread;
- out += o_offset * TOTAL_BLOCKS_COUNT * HEAD_DIM + block_idx * HEAD_DIM +
- thread_context.simd_lane_id * elements_per_thread;
- sums += o_offset * TOTAL_BLOCKS_COUNT + block_idx;
- maxs += o_offset * TOTAL_BLOCKS_COUNT + block_idx;
-
- for (uint i = 0; i < elements_per_thread; i++) {
- q[i] = static_cast<U>(scale) * queries[i];
- }
- U max_score = -1e9;
- U sum_exp_score = 0;
- if (has_sinks && block_idx == 0) {
- max_score = static_cast<U>(sinks[head_idx]);
- sum_exp_score = 1;
- }
-
- // For each key position
- for (uint i = block_idx; i < sequence_length; i += TOTAL_BLOCKS_COUNT) {
- if (should_use_key(
- ring_params,
- trie,
- sliding_window_size,
- q_seq_idx,
- prefix_length,
- suffix_position,
- query_position,
- i,
- is_kv_cache_ring,
- is_causal,
- is_trie,
- is_sliding_window
- )) {
- // Compute score
- U score = 0;
- for (uint j = 0; j < elements_per_thread; j++) {
- score += q[j] * static_cast<U>(keys[j]);
- }
- score = simd_sum(score);
-
- // Online softmax update
- U new_max = max(max_score, score);
- U factor = fast::exp(max_score - new_max);
- U exp_score = fast::exp(score - new_max);
- max_score = new_max;
- sum_exp_score = sum_exp_score * factor + exp_score;
-
- for (uint j = 0; j < elements_per_thread; j++) {
- o[j] = o[j] * factor + exp_score * static_cast<U>(values[j]);
- }
- }
-
- keys += TOTAL_BLOCKS_COUNT * k_seq_stride;
- values += TOTAL_BLOCKS_COUNT * v_seq_stride;
- }
-
- // Write partial output
- if (thread_context.simd_lane_id == 0) {
- sums[0] = sum_exp_score;
- maxs[0] = max_score;
- }
- for (uint i = 0; i < elements_per_thread; i++) {
- out[i] = o[i];
- }
-}
-
-template <typename T, uint HEAD_DIM>
-VARIANTS(T, bfloat)
-VARIANTS(HEAD_DIM, 64, 128, 256, 512)
-KERNEL(AttentionTwoPass2)(
- const device float* partials,
- const device float* sums,
- const device float* maxs,
- device T* out,
- const device T* gate OPTIONAL(has_gate),
- const constant uint& num_heads,
- const constant uint& suffix_length,
- const constant uint& gate_row_stride OPTIONAL(has_gate),
- const bool has_gate SPECIALIZE,
- const ThreadContext thread_context,
- const uint head_idx GROUPS(num_heads),
- const uint q_seq_idx GROUPS(suffix_length),
- const uint tid THREADS(1024)
-) {
- constexpr uint elements_per_thread = HEAD_DIM / METAL_SIMD_SIZE;
-
- typedef float U;
-
- const uint o_offset = q_seq_idx * num_heads + head_idx;
-
- sums += o_offset * TOTAL_BLOCKS_COUNT;
- maxs += o_offset * TOTAL_BLOCKS_COUNT;
-
- // Find global max across all blocks (each lane handles strided blocks)
- U max_score = -1e9;
- for (uint b = thread_context.simd_lane_id; b < TOTAL_BLOCKS_COUNT; b += METAL_SIMD_SIZE) {
- max_score = max(max_score, maxs[b]);
- }
- U new_max = simd_max(max_score);
-
- // Find global sum across all blocks
- U sum_exp = 0;
- for (uint b = thread_context.simd_lane_id; b < TOTAL_BLOCKS_COUNT; b += METAL_SIMD_SIZE) {
- sum_exp += sums[b] * fast::exp(maxs[b] - new_max);
- }
- U sum_exp_score = simd_sum(sum_exp);
-
- // Combine partial outputs — each lane reads a different block,
- // simd_sum reduces across blocks directly (no shared memory needed)
- thread U o[elements_per_thread] = {0};
-
- for (uint chunk = 0; chunk < TOTAL_BLOCKS_COUNT; chunk += METAL_SIMD_SIZE) {
- uint block_idx = chunk + thread_context.simd_lane_id;
- U factor = (block_idx < TOTAL_BLOCKS_COUNT) ? fast::exp(maxs[block_idx] - new_max) : 0;
-
- const device float* block_partials = partials + o_offset * TOTAL_BLOCKS_COUNT * HEAD_DIM + block_idx * HEAD_DIM +
- thread_context.simdgroup_index * elements_per_thread;
-
- for (uint i = 0; i < elements_per_thread; i++) {
- U val = (block_idx < TOTAL_BLOCKS_COUNT) ? block_partials[i] * factor : 0;
- o[i] += simd_sum(val);
- }
- }
-
- // Write the output
- if (thread_context.simd_lane_id == 0) {
- out += o_offset * HEAD_DIM + thread_context.simdgroup_index * elements_per_thread;
- for (uint i = 0; i < elements_per_thread; i++) {
- T result = static_cast<T>(o[i] / sum_exp_score);
- if (has_gate) {
- const uint channel = thread_context.simdgroup_index * elements_per_thread + i;
- result = uzu::apply_sigmoid_gate(result, gate[q_seq_idx * gate_row_stride + head_idx * HEAD_DIM + channel]);
- }
- out[i] = result;
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs
deleted file mode 100644
index c5d8a3a87..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-use thiserror::Error;
-
-use crate::backends::metal::error::MetalError;
-
-#[derive(Debug, Error)]
-pub enum AttentionMetalError {
- #[error("INT8 KV unsupported for this attention config")]
- UnsupportedInt8KV,
- #[error("Backend error: {0}")]
- Backend(#[from] MetalError),
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs
deleted file mode 100644
index a403cc7d4..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-use std::collections::{HashMap, hash_map::Entry};
-
-use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
-
-use super::FullPrecisionInput;
-use crate::{
- backends::{
- common::{
- Backend, BufferRef, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernelConfig},
- },
- metal::{
- Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError,
- gpu_types::attention::AttnParams, kernel::AttentionGemmMetalKernel,
- },
- },
- data_type::DataType,
-};
-
-pub struct AttentionGemm {
- kernels: Mutex<HashMap<AttentionGemmKey, AttentionGemmMetalKernel>>,
- head_dim: u32,
- num_groups: u32,
- num_q_heads: u32,
- sliding_window_size: Option<u32>,
- scale: Option<f32>,
- data_type: DataType,
- simd_bk: u32,
- is_kv_cache_ring: bool,
- is_causal: 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,
- is_trie: 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 AttentionGemm {
- pub fn is_supported(config: &AttentionKernelConfig) -> bool {
- matches!(config.head_dim, 64 | 128 | 256) && config.data_type == DataType::BF16
- }
-
- pub fn new(config: &AttentionKernelConfig) -> Self {
- let simd_bk = if config.head_dim < 128 {
- 32
- } else {
- 16
- };
- Self {
- kernels: Mutex::new(HashMap::new()),
- head_dim: config.head_dim,
- num_groups: config.num_groups,
- num_q_heads: config.num_q_heads,
- sliding_window_size: config.sliding_window_size,
- scale: config.scale,
- data_type: config.data_type,
- simd_bk,
- is_kv_cache_ring: config.is_kv_cache_ring,
- is_causal: config.is_causal,
- is_sliding_window: config.sliding_window_size.is_some(),
- has_sinks: config.has_sinks,
- }
- }
-
- fn get_or_create(
- &self,
- context: &MetalContext,
- key: AttentionGemmKey,
- ) -> Result<MappedMutexGuard<'_, AttentionGemmMetalKernel>, MetalError> {
- let mut kernels = self.kernels.lock();
- 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,
- key.use_mxu,
- key.align_q,
- key.align_k,
- self.is_kv_cache_ring,
- self.is_causal,
- key.is_trie,
- self.is_sliding_window,
- self.has_sinks,
- )?;
- entry.insert(kernel);
- }
- Ok(MutexGuard::map(kernels, |kernels| kernels.get_mut(&key).expect("kernel was just initialized")))
- }
-
- pub fn encode(
- &self,
- input: FullPrecisionInput<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
- let mut output = command_buffer
- .allocate_scratch_for_shape(&[arguments.suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;
-
- let use_mxu =
- arguments.suffix_length >= 64 && matches!(self.head_dim, 64 | 128) && command_buffer.context().supports_mxu;
- 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, self.head_dim],
- k_strides: [0, self.head_dim, self.num_groups * self.head_dim],
- v_strides: [0, self.head_dim, self.num_groups * self.head_dim],
- o_strides: [0, self.head_dim, self.num_q_heads * self.head_dim],
- gqa_factor: self.num_q_heads / self.num_groups,
- scale: self.scale.unwrap_or(1.0 / (self.head_dim as f32).sqrt()),
- q_len: arguments.suffix_length,
- k_len: arguments.cache.prefix_len() + arguments.suffix_length,
- q_off: arguments.cache.prefix_len(),
- 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,
- is_trie: arguments.trie.is_some(),
- };
- let kernel = self.get_or_create(command_buffer.context(), key)?;
- kernel.encode(
- input.queries,
- input.keys,
- input.values,
- &mut output,
- params,
- arguments.cache.ring_params(),
- arguments.trie,
- self.sliding_window_size,
- arguments.sinks,
- self.num_q_heads,
- arguments.suffix_length,
- command_buffer,
- );
- Ok(output)
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal
deleted file mode 100644
index a764b3053..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal
+++ /dev/null
@@ -1,396 +0,0 @@
-#include <metal_stdlib>
-#include "../../common/dsl.h"
-#include "../../common/integral_constant.h"
-#include "../../common/thread_context.h"
-#include "../../matmul/common/fragment.h"
-#include "../../matmul/common/loader.h"
-#include "../../matmul/common/mxu_fragment/ops.h"
-#include "../../generated/attention.h"
-#include "../../generated/trie.h"
-#include "layout.h"
-
-using namespace metal;
-using namespace uzu::matmul;
-using namespace uzu::attention;
-using namespace uzu::trie;
-
-template <typename T, uint BK, uint BD, uint HEAD_DIM_SLICES, bool USE_MXU>
-VARIANTS(T, bfloat)
-VARIANTS(BK, 16, 32)
-VARIANTS(BD, 128, 256)
-VARIANTS(HEAD_DIM_SLICES, 1, 2, 4, 8)
-VARIANTS(USE_MXU, false, true)
-CONSTRAINT((BK == 16) == (HEAD_DIM_SLICES == 1))
-CONSTRAINT(HEAD_DIM_SLICES != 1 || BD == 128)
-CONSTRAINT(!USE_MXU || HEAD_DIM_SLICES == BD / 64)
-CONSTRAINT(USE_MXU || BD == 256 || HEAD_DIM_SLICES == 1 || HEAD_DIM_SLICES == BD / 32)
-KERNEL(AttentionGemmGrouped)(
- const device T* q,
- const device T* k,
- const device T* v,
- device T* o OPTIONAL(!split_kv),
- device T* partials OPTIONAL(split_kv),
- device float* partial_maxs OPTIONAL(split_kv),
- device float* partial_sums OPTIONAL(split_kv),
- const device TrieNode* trie OPTIONAL(is_trie),
- const constant AttnParams& params,
- const constant uint& query_tiles,
- const constant uint& kv_heads,
- const constant uint& num_splits,
- const bool split_kv SPECIALIZE,
- const bool is_causal SPECIALIZE,
- const bool is_trie SPECIALIZE,
- threadgroup float scratch[AttentionGemmGroupedLayout<BK, BD, HEAD_DIM_SLICES, USE_MXU>::THREADGROUP_SCRATCH_FLOATS],
- const ThreadContext thread_context,
- const uint tile_split_flat GROUPS(query_tiles * num_splits),
- const uint kv_head_idx GROUPS(kv_heads),
- const uint lid THREADS(ATTENTION_GQA_SIMDGROUPS * METAL_SIMD_SIZE)
-) {
- using Layout = AttentionGemmGroupedLayout<BK, BD, HEAD_DIM_SLICES, USE_MXU>;
- using Ops = typename Layout::Ops;
- using AccumType = float;
- constexpr bool GROUP_FOUR_Q_HEADS = HEAD_DIM_SLICES == 1;
- using InputType = metal::conditional_t<USE_MXU || GROUP_FOUR_Q_HEADS, T, AccumType>;
-
- constexpr int TILE_ROWS = Layout::TILE_ROWS;
- constexpr int SLICE_COLS = Layout::SLICE_COLS;
- constexpr int BLOCK_ROWS = Layout::BLOCK_ROWS;
- constexpr int SCORE_TILE_ELEMENTS = Layout::SCORE_TILE_ELEMENTS;
- constexpr int KEY_COL_FRAGMENTS = int(BK) / Ops::FRAGMENT_COLS;
- constexpr int HEAD_DIM_FRAGMENTS_PER_SLICE = SLICE_COLS / Ops::FRAGMENT_ROWS;
- constexpr int VALUE_COL_FRAGMENTS = SLICE_COLS / Ops::FRAGMENT_COLS;
- constexpr int PV_COL_FRAGMENTS = VALUE_COL_FRAGMENTS < 8 ? VALUE_COL_FRAGMENTS : 8;
- constexpr int PV_CHUNKS = VALUE_COL_FRAGMENTS / PV_COL_FRAGMENTS;
- constexpr int ROWS_PER_LANE = Ops::THREAD_ELEMENT_ROWS;
-
- static_assert(Layout::SIMDGROUPS == 8, "requires eight simdgroups");
- static_assert(KEY_COL_FRAGMENTS % 2 == 0, "QK fragments must be even");
- static_assert(VALUE_COL_FRAGMENTS % 2 == 0, "PV fragments must be even");
- static_assert(VALUE_COL_FRAGMENTS % PV_COL_FRAGMENTS == 0, "PV fragments must divide into chunks");
-
- using QueryFragment = OperandFragment<InputType, 1, 1, Ops>;
- using KeyFragment = OperandFragment<InputType, 1, KEY_COL_FRAGMENTS, Ops, ReadTranspose>;
- using ValueFragment = OperandFragment<InputType, KEY_COL_FRAGMENTS, PV_COL_FRAGMENTS, Ops>;
- using ScoreFragment = Fragment<AccumType, 1, KEY_COL_FRAGMENTS, Ops>;
- using OutputFragment = Fragment<AccumType, 1, VALUE_COL_FRAGMENTS, Ops>;
- using PvOutputFragment = Fragment<AccumType, 1, PV_COL_FRAGMENTS, Ops>;
- using KvBlockStorage = metal::conditional_t<GROUP_FOUR_Q_HEADS, ThreadgroupBlockStorage, DeviceBlockStorage>;
- using KvBlockSource =
- BlockSource<T, BK, BD, Layout::SHARED_KV_ROW_STRIDE, Layout::SIMDGROUPS * METAL_SIMD_SIZE, KvBlockStorage>;
-
- const ushort lane = ushort(thread_context.simd_lane_id);
- const ushort simdgroup_index = ushort(thread_context.simdgroup_index);
- const ushort band = simdgroup_index / ushort(HEAD_DIM_SLICES);
- const ushort slice = simdgroup_index % ushort(HEAD_DIM_SLICES);
-
- const uint query_tile_idx = split_kv ? (tile_split_flat % query_tiles) : tile_split_flat;
- const uint split_idx = split_kv ? (tile_split_flat / query_tiles) : 0u;
-
- const uint grouped_rows = params.gqa_factor * params.q_len;
- const uint head_in_group = GROUP_FOUR_Q_HEADS
- ? uint(band / 2)
- : (query_tile_idx * uint(BLOCK_ROWS) + uint(band) * uint(TILE_ROWS)) / params.q_len;
- const uint query_base = GROUP_FOUR_Q_HEADS
- ? query_tile_idx * uint(2 * TILE_ROWS) + uint(band % 2) * uint(TILE_ROWS)
- : (query_tile_idx * uint(BLOCK_ROWS) + uint(band) * uint(TILE_ROWS)) % params.q_len;
- const uint row_base = head_in_group * params.q_len + query_base;
- const uint q_head_idx = kv_head_idx * params.gqa_factor + head_in_group;
-
- const uint query_row_stride = params.q_strides[2];
- const uint key_row_stride = params.k_strides[2];
- const uint value_row_stride = params.v_strides[2];
- const uint output_row_stride = params.o_strides[2];
- const uint slice_offset = uint(slice) * uint(SLICE_COLS);
-
- q += size_t(q_head_idx) * params.q_strides[1] + size_t(query_base) * query_row_stride + slice_offset;
- k += size_t(kv_head_idx) * params.k_strides[1] + slice_offset;
- v += size_t(kv_head_idx) * params.v_strides[1] + slice_offset;
-
- QueryFragment query_frags[HEAD_DIM_FRAGMENTS_PER_SLICE];
- {
- auto query_source = fragment_source(q, int(query_row_stride));
- const uint valid_rows = row_base < grouped_rows ? grouped_rows - row_base : 0u;
- if (valid_rows < uint(TILE_ROWS)) {
- query_source = query_source.bounded(short(valid_rows), short(Ops::FRAGMENT_COLS));
- }
- METAL_PRAGMA_UNROLL
- for (short head_dim_fragment_idx = 0; head_dim_fragment_idx < HEAD_DIM_FRAGMENTS_PER_SLICE;
- ++head_dim_fragment_idx) {
- query_frags[head_dim_fragment_idx].load_from(
- lane,
- query_source.advanced(head_dim_fragment_idx * Ops::FRAGMENT_ROWS)
- );
- if constexpr (GROUP_FOUR_Q_HEADS) {
- const InputType query_scale = static_cast<InputType>(params.scale * M_LOG2E_F);
- query_frags[head_dim_fragment_idx].map_coords(lane, [&](short, short, InputType value) {
- return value * query_scale;
- });
- }
- }
- }
-
- OutputFragment output;
- output.clear();
-
- AccumType max_score[ROWS_PER_LANE];
- AccumType sum_score[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- max_score[r] = -INFINITY;
- sum_score[r] = AccumType(0);
- }
-
- const uint prefix_length = params.q_off;
- const uint key_length = params.k_len;
- const short2 score_position = ScoreFragment::get_position(lane);
- uint last_visible_key[ROWS_PER_LANE];
- ulong row_trie_mask[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (ushort r = 0; r < ROWS_PER_LANE; ++r) {
- last_visible_key[r] = 0;
- row_trie_mask[r] = 0ul;
- }
- if (is_causal || is_trie) {
- METAL_PRAGMA_UNROLL
- for (ushort r = 0; r < ROWS_PER_LANE; ++r) {
- const uint row = row_base + uint(score_position.y) + uint(r) * uint(Ops::THREAD_ELEMENT_ROW_STRIDE);
- last_visible_key[r] = prefix_length + row % params.q_len;
- }
- if (is_trie) {
- const ulong all_suffix_keys = (params.q_len >= 64u) ? ~0ul : ((1ul << params.q_len) - 1ul);
- METAL_PRAGMA_UNROLL
- for (ushort r = 0; r < ROWS_PER_LANE; ++r) {
- row_trie_mask[r] = is_causal ? 0ul : all_suffix_keys;
- }
- if (is_causal) {
- for (uint node_index = 0; node_index < params.q_len; ++node_index) {
- const TrieNode node = trie[node_index];
- METAL_PRAGMA_UNROLL
- for (ushort r = 0; r < ROWS_PER_LANE; ++r) {
- const uint query_index = last_visible_key[r] - prefix_length;
- if (query_index >= node.trie_start && query_index <= node.trie_end) {
- row_trie_mask[r] |= (1ul << node_index);
- }
- }
- }
- }
- }
- }
-
- threadgroup float* exchange_slot = scratch + simdgroup_index * SCORE_TILE_ELEMENTS;
- threadgroup T* kv_shared = reinterpret_cast<threadgroup T*>(scratch);
- const ushort band_exchange_base = band * ushort(HEAD_DIM_SLICES);
- const uint key_block_stride = uint(BK) * key_row_stride;
- const uint value_block_stride = uint(BK) * value_row_stride;
-
- const uint block_begin = split_kv ? (split_idx * params.nk) / num_splits : 0u;
- uint block_end = split_kv ? ((split_idx + 1u) * params.nk) / num_splits : params.nk;
-
- if (is_causal) {
- const uint tile_first_row = query_tile_idx * uint(BLOCK_ROWS);
- const uint tile_last_row = min(tile_first_row + uint(BLOCK_ROWS) - 1u, grouped_rows - 1u);
- const uint max_query_index =
- GROUP_FOUR_Q_HEADS
- ? min((query_tile_idx + 1u) * uint(2 * TILE_ROWS) - 1u, params.q_len - 1u)
- : ((tile_first_row / params.q_len == tile_last_row / params.q_len) ? (tile_last_row % params.q_len)
- : (params.q_len - 1u));
- const uint causal_blocks = (uint(prefix_length) + max_query_index + uint(BK)) / uint(BK);
- block_end = min(block_end, causal_blocks);
- }
-
- const uint tail_keys = params.k_rem;
- const uint block_count = block_end > block_begin ? block_end - block_begin : 0u;
- const bool owns_tail_block = (tail_keys != 0u) && (block_count > 0u) && (block_end == params.nk);
- const uint full_blocks = owns_tail_block ? block_count - 1u : block_count;
-
- k += size_t(block_begin) * key_block_stride;
- v += size_t(block_begin) * value_block_stride;
-
- const AccumType score_scale = GROUP_FOUR_Q_HEADS ? AccumType(1) : AccumType(params.scale) * AccumType(M_LOG2E_F);
- const AccumType masked_score_pre_scale = (static_cast<AccumType>(-1e9f) * M_LOG2E_F) / score_scale;
- const uint first_key = block_begin * uint(BK);
-
- auto accumulate_kv_block = [&](const uint kb, auto tail_flag) {
- constexpr bool IS_TAIL = decltype(tail_flag)::value;
-
- ScoreFragment score;
- score.clear();
- {
- KvBlockSource key_source(
- k + size_t(kb) * key_block_stride,
- int(key_row_stride),
- kv_shared,
- IS_TAIL ? short(tail_keys) : short(BK),
- thread_context
- );
- key_source.prepare();
- METAL_PRAGMA_UNROLL
- for (short head_dim_fragment_idx = 0; head_dim_fragment_idx < HEAD_DIM_FRAGMENTS_PER_SLICE;
- ++head_dim_fragment_idx) {
- KeyFragment key_fragment;
- key_source.load(key_fragment, head_dim_fragment_idx * Ops::FRAGMENT_ROWS);
- simdgroup_barrier(mem_flags::mem_none);
- fragment_mma(score, query_frags[head_dim_fragment_idx], key_fragment);
- }
- }
-
- if constexpr (HEAD_DIM_SLICES > 1) {
- threadgroup_barrier(mem_flags::mem_threadgroup);
- score.store(lane, exchange_slot, int(BK));
- threadgroup_barrier(mem_flags::mem_threadgroup);
-
- thread AccumType* score_elements = score.elements();
- METAL_PRAGMA_UNROLL
- for (ushort j = 1; j < ushort(HEAD_DIM_SLICES); ++j) {
- const ushort other = (slice + j) % ushort(HEAD_DIM_SLICES);
- ScoreFragment partial;
- partial.load_from(lane, fragment_source(scratch + (band_exchange_base + other) * SCORE_TILE_ELEMENTS, int(BK)));
- thread AccumType* partial_elements = partial.elements();
- METAL_PRAGMA_UNROLL
- for (ushort e = 0; e < ScoreFragment::ELEMENTS_PER_FRAGMENT; ++e) {
- score_elements[e] += partial_elements[e];
- }
- }
- }
-
- const uint key_base = first_key + kb * uint(BK);
- const bool masked_block = IS_TAIL || ((is_causal || is_trie) && (key_base + uint(BK) > prefix_length));
- if (masked_block) {
- score.map_coords(lane, [&](short row, short col, AccumType value) UZU_ALWAYS_INLINE {
- const ushort lane_row = ushort(row - score_position.y) / Ops::THREAD_ELEMENT_ROW_STRIDE;
- const uint key = key_base + uint(col);
- bool visible = key < key_length;
- if (is_trie) {
- visible = visible &&
- (key < prefix_length || ((row_trie_mask[lane_row] >> ulong(key - prefix_length)) & 1ul) != 0ul);
- } else if (is_causal) {
- visible = visible && (key <= last_visible_key[lane_row]);
- }
- return visible ? value : masked_score_pre_scale;
- });
- }
-
- AccumType block_max[ROWS_PER_LANE];
- score.row_reduce(block_max, -INFINITY, [](AccumType a, AccumType b) { return metal::max(a, b); });
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- block_max[r] *= score_scale;
- }
-
- AccumType new_max[ROWS_PER_LANE];
- AccumType rescale[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- new_max[r] = metal::max(max_score[r], block_max[r]);
- rescale[r] = fast::exp2(max_score[r] - new_max[r]);
- max_score[r] = new_max[r];
- sum_score[r] *= rescale[r];
- }
-
- score.map_rows(new_max, [score_scale](AccumType value, AccumType m) {
- return fast::exp2(value * score_scale - m);
- });
-
- AccumType block_sum[ROWS_PER_LANE];
- score.row_reduce(block_sum, AccumType(0), [](AccumType a, AccumType b) { return a + b; });
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- sum_score[r] += block_sum[r];
- }
-
- output.map_rows(rescale, [](AccumType value, AccumType f) { return value * f; });
-
- {
- KvBlockSource value_block(
- v + size_t(kb) * value_block_stride,
- int(value_row_stride),
- kv_shared,
- IS_TAIL ? short(tail_keys) : short(BK),
- thread_context
- );
- value_block.prepare();
- METAL_PRAGMA_UNROLL
- for (ushort chunk = 0; chunk < PV_CHUNKS; ++chunk) {
- const ushort first_col = chunk * PV_COL_FRAGMENTS;
- const int chunk_offset = first_col * Ops::FRAGMENT_COLS;
- ValueFragment value_fragment;
- value_block.load(value_fragment, chunk_offset);
- simdgroup_barrier(mem_flags::mem_none);
-
- PvOutputFragment chunk_output;
- METAL_PRAGMA_UNROLL
- for (ushort col = 0; col < PV_COL_FRAGMENTS; ++col) {
- chunk_output.fragment_at(0, col) = output.fragment_at(0, first_col + col);
- }
- fragment_mma(chunk_output, score, value_fragment);
- METAL_PRAGMA_UNROLL
- for (ushort col = 0; col < PV_COL_FRAGMENTS; ++col) {
- output.fragment_at(0, first_col + col) = chunk_output.fragment_at(0, col);
- }
- }
- }
- };
-
- for (uint kb = 0; kb < full_blocks; ++kb) {
- accumulate_kv_block(kb, uzu::false_type{});
- }
- if (owns_tail_block) {
- accumulate_kv_block(full_blocks, uzu::true_type{});
- }
-
- if (split_kv) {
- const uint split_head_row = (split_idx * kv_heads + kv_head_idx) * query_tiles * uint(BLOCK_ROWS);
- const uint partial_row = split_head_row + row_base;
- device T* partial_tile = partials + size_t(partial_row) * BD;
- output.store(lane, partial_tile + slice_offset, int(BD));
-
- if (slice == 0) {
- const short2 position = OutputFragment::get_position(lane);
- if (position.x == 0) {
- const uint row_base_in_tile = partial_row;
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- const uint row = row_base_in_tile + uint(position.y + r * Ops::THREAD_ELEMENT_ROW_STRIDE);
- partial_maxs[row] = max_score[r];
- partial_sums[row] = sum_score[r];
- }
- }
- }
- } else {
- AccumType inverse_sum[ROWS_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (int r = 0; r < ROWS_PER_LANE; ++r) {
- inverse_sum[r] = AccumType(1) / sum_score[r];
- }
- output.map_rows(inverse_sum, [](AccumType value, AccumType s) { return value * s; });
-
- if (params.q_len % uint(TILE_ROWS) == 0u) {
- if (row_base < grouped_rows) {
- device T* destination =
- o + size_t(q_head_idx) * params.o_strides[1] + size_t(query_base) * output_row_stride + slice_offset;
- output.store(lane, destination, int(output_row_stride));
- }
- } else {
- const short2 position = OutputFragment::get_position(lane);
- thread AccumType* output_elements = output.elements();
- METAL_PRAGMA_UNROLL
- for (ushort r = 0; r < ROWS_PER_LANE; ++r) {
- const uint row = row_base + uint(position.y) + uint(r) * uint(Ops::THREAD_ELEMENT_ROW_STRIDE);
- if (row < grouped_rows) {
- const uint row_head = row / params.q_len;
- const uint row_position = row - row_head * params.q_len;
- device T* destination = o + (size_t(kv_head_idx) * params.gqa_factor + row_head) * params.o_strides[1] +
- size_t(row_position) * output_row_stride + slice_offset + position.x;
- METAL_PRAGMA_UNROLL
- for (ushort fragment_col = 0; fragment_col < VALUE_COL_FRAGMENTS; ++fragment_col) {
- METAL_PRAGMA_UNROLL
- for (ushort col = 0; col < Ops::THREAD_ELEMENT_COLS; ++col) {
- const ushort element = fragment_col * Ops::ELEMENTS_PER_THREAD + r * Ops::THREAD_ELEMENT_COLS + col;
- destination[fragment_col * Ops::FRAGMENT_COLS + col] = static_cast<T>(output_elements[element]);
- }
- }
- }
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine.metal
deleted file mode 100644
index d0a099f06..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine.metal
+++ /dev/null
@@ -1,65 +0,0 @@
-#include <metal_stdlib>
-#include "../../common/dsl.h"
-#include "../../generated/attention.h"
-#include "../../common/sigmoid_gate.h"
-
-using namespace metal;
-using namespace uzu::attention;
-
-template <typename T, uint BD>
-VARIANTS(T, bfloat)
-VARIANTS(BD, 128, 256)
-KERNEL(AttentionGemmGroupedCombine)(
- const device T* partials,
- const device float* partial_maxs,
- const device float* partial_sums,
- device T* o,
- const device T* gate OPTIONAL(has_gate),
- const constant AttnParams& params,
- const constant uint& grouped_rows,
- const constant uint& padded_rows,
- const constant uint& kv_heads,
- const constant uint& num_splits,
- const constant uint& gate_row_stride OPTIONAL(has_gate),
- const bool has_gate SPECIALIZE,
- const uint grouped_row_idx GROUPS(grouped_rows),
- const uint kv_head_idx GROUPS(kv_heads),
- const uint column THREADS(BD)
-) {
- const size_t row = size_t(kv_head_idx) * padded_rows + grouped_row_idx;
- const uint split_rows = kv_heads * padded_rows;
- const uint head_in_group = grouped_row_idx / params.q_len;
- const uint query_position = grouped_row_idx - head_in_group * params.q_len;
- const uint q_head_idx = kv_head_idx * params.gqa_factor + head_in_group;
- const device float* row_maxs = partial_maxs + row;
- const device float* row_sums = partial_sums + row;
- const device T* row_partials = partials + row * BD + column;
-
- float numerator = 0.0f;
- float denominator = 0.0f;
- float global_max = -INFINITY;
- for (uint s = 0; s < num_splits; ++s) {
- if (row_sums[s * split_rows] > 0.0f) {
- global_max = metal::max(global_max, row_maxs[s * split_rows]);
- }
- }
- if (global_max > -INFINITY) {
- for (uint s = 0; s < num_splits; ++s) {
- const float split_sum = row_sums[s * split_rows];
- if (split_sum <= 0.0f) {
- continue;
- }
- const float rescale = fast::exp2(row_maxs[s * split_rows] - global_max);
- const float weight = rescale * split_sum;
- denominator += weight;
- numerator += rescale * float(row_partials[size_t(s) * split_rows * BD]);
- }
- }
- const float mean = denominator > 0.0f ? numerator / denominator : 0.0f;
- T result = static_cast<T>(mean);
- if (has_gate) {
- result = uzu::apply_sigmoid_gate(result, gate[query_position * gate_row_stride + q_head_idx * BD + column]);
- }
- o += size_t(q_head_idx) * params.o_strides[1] + size_t(query_position) * params.o_strides[2] + column;
- o[0] = result;
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/layout.h b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/layout.h
deleted file mode 100644
index 26e3feb95..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/layout.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#pragma once
-
-#include <metal_stdlib>
-#include "../../common/defines.h"
-#include "../../common/dsl.h"
-#include "../../matmul/common/mxu_fragment/ops.h"
-#include "../../matmul/common/simdgroup_fragment_ops.h"
-
-using namespace metal;
-
-#define ATTENTION_GQA_SIMDGROUPS 8
-
-template <uint BK, uint BD, uint HEAD_DIM_SLICES, bool USE_MXU = true>
-struct AttentionGemmGroupedLayout {
- using Ops = metal::conditional_t<USE_MXU, uzu::matmul::MxuFragmentOps<>, uzu::matmul::SimdgroupFragmentOps>;
-
- UZU_CONST int SIMDGROUPS = ATTENTION_GQA_SIMDGROUPS;
- UZU_CONST int TILE_ROWS = Ops::FRAGMENT_ROWS;
- UZU_CONST int SLICE_COLS = int(BD) / int(HEAD_DIM_SLICES);
- UZU_CONST int BANDS = SIMDGROUPS / int(HEAD_DIM_SLICES);
- UZU_CONST int BLOCK_ROWS = BANDS * TILE_ROWS;
- UZU_CONST int SCORE_TILE_ELEMENTS = TILE_ROWS * int(BK);
- UZU_CONST int SHARED_KV_ROW_STRIDE = int(BD) + 8;
- UZU_CONST int THREADGROUP_SCRATCH_FLOATS =
- HEAD_DIM_SLICES == 1 ? int(BK) * SHARED_KV_ROW_STRIDE / 2 : SIMDGROUPS * SCORE_TILE_ELEMENTS;
-};
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs
deleted file mode 100644
index ba8818d3e..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs
+++ /dev/null
@@ -1,308 +0,0 @@
-use std::collections::{HashMap, hash_map::Entry};
-
-use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
-
-use super::FullPrecisionInput;
-use crate::{
- backends::{
- common::{
- Backend, BufferMut, BufferRef, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernelConfig},
- },
- metal::{
- Metal,
- command_buffer::MetalCommandBufferEncoding,
- context::MetalContext,
- error::MetalError,
- gpu_types::attention::AttnParams,
- kernel::{AttentionGemmGroupedCombineMetalKernel, AttentionGemmGroupedMetalKernel},
- },
- },
- data_type::DataType,
-};
-
-pub(super) mod policy;
-use policy::{MAX_TRIE_SUFFIX, SplitGeometry, choose_splits};
-
-use super::MaskKind;
-
-const SIMDGROUPS_PER_THREADGROUP: u32 = 8;
-const SLICE_COLS: u32 = 64;
-const MXU_TILE_ROWS: u32 = 16;
-const SIMDGROUP_TILE_ROWS: u32 = 8;
-const BLOCK_K: u32 = 32;
-
-pub fn query_rows_per_threadgroup(head_dim: u32) -> u32 {
- SIMDGROUPS_PER_THREADGROUP / (head_dim / SLICE_COLS) * MXU_TILE_ROWS
-}
-
-struct AttentionGemmGroupedMetal {
- kernel: AttentionGemmGroupedMetalKernel,
- split_kernel: AttentionGemmGroupedMetalKernel,
- combine: AttentionGemmGroupedCombineMetalKernel,
- head_dim: u32,
- num_groups: u32,
- num_q_heads: u32,
- scale: Option<f32>,
- gate_row_stride: Option<u32>,
- query_rows_per_threadgroup: u32,
- block_k: u32,
- mask: MaskKind,
-}
-
-impl AttentionGemmGroupedMetal {
- fn new_fixed(
- context: &MetalContext,
- config: &AttentionKernelConfig,
- head_dim_slices: u32,
- mask: MaskKind,
- ) -> Result<Self, MetalError> {
- let tile_rows = if context.supports_mxu {
- MXU_TILE_ROWS
- } else {
- SIMDGROUP_TILE_ROWS
- };
- let block_k = if head_dim_slices == 1 {
- 16
- } else {
- BLOCK_K
- };
- assert!(matches!(config.head_dim, 128 | 256), "head_dim must be 128 or 256");
- assert_eq!(config.num_q_heads % config.num_groups, 0, "num_q_heads must be divisible by num_groups");
- let new_kernel = |split| {
- AttentionGemmGroupedMetalKernel::new(
- context,
- DataType::BF16,
- block_k,
- config.head_dim,
- head_dim_slices,
- context.supports_mxu,
- split,
- mask.is_causal(),
- mask.is_trie(),
- )
- };
- let combine = AttentionGemmGroupedCombineMetalKernel::new(
- context,
- DataType::BF16,
- config.head_dim,
- config.gate_row_stride.is_some(),
- )?;
- Ok(Self {
- kernel: new_kernel(false)?,
- split_kernel: new_kernel(true)?,
- combine,
- head_dim: config.head_dim,
- num_groups: config.num_groups,
- num_q_heads: config.num_q_heads,
- scale: config.scale,
- gate_row_stride: config.gate_row_stride,
- query_rows_per_threadgroup: SIMDGROUPS_PER_THREADGROUP / head_dim_slices * tile_rows,
- block_k,
- mask,
- })
- }
-
- fn encode(
- &self,
- queries: impl BufferRef<Backend = Metal>,
- keys: impl BufferRef<Backend = Metal>,
- values: impl BufferRef<Backend = Metal>,
- output: impl BufferMut<Backend = Metal>,
- trie: Option<impl BufferRef<Backend = Metal>>,
- gate: Option<impl BufferRef<Backend = Metal>>,
- suffix_length: u32,
- kv_length: u32,
- num_splits: u32,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<bool, MetalError> {
- let params = self.params(suffix_length, kv_length);
- let grouped_rows = self.num_q_heads / self.num_groups * suffix_length;
- let query_tiles = grouped_rows.div_ceil(self.query_rows_per_threadgroup);
- assert_eq!(trie.is_some(), self.mask.is_trie(), "trie presence must match mask");
-
- if num_splits == 1 {
- self.kernel.encode(
- queries,
- keys,
- values,
- Some(output),
- None::<&mut <Metal as Backend>::ScratchBuffer>,
- None::<&mut <Metal as Backend>::ScratchBuffer>,
- None::<&mut <Metal as Backend>::ScratchBuffer>,
- trie,
- params,
- query_tiles,
- self.num_groups,
- 1,
- command_buffer,
- );
- return Ok(false);
- }
-
- let partial_rows = self.num_groups * query_tiles * num_splits * self.query_rows_per_threadgroup;
- let mut partials = command_buffer.allocate_scratch_for_shape(&[partial_rows, self.head_dim], DataType::BF16)?;
- let mut partial_maxs = command_buffer.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;
- let mut partial_sums = command_buffer.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;
-
- self.split_kernel.encode(
- queries,
- keys,
- values,
- None::<&mut <Metal as Backend>::ScratchBuffer>,
- Some(&mut partials),
- Some(&mut partial_maxs),
- Some(&mut partial_sums),
- trie,
- params,
- query_tiles,
- self.num_groups,
- num_splits,
- command_buffer,
- );
-
- self.combine.encode(
- &partials,
- &partial_maxs,
- &partial_sums,
- output,
- gate,
- params,
- grouped_rows,
- query_tiles * self.query_rows_per_threadgroup,
- self.num_groups,
- num_splits,
- self.gate_row_stride,
- command_buffer,
- );
- Ok(gate.is_some())
- }
-
- fn params(
- &self,
- suffix_length: u32,
- kv_length: u32,
- ) -> AttnParams {
- assert!(suffix_length > 0 && kv_length > 0, "lengths must be positive");
- assert!(kv_length >= suffix_length, "kv_length must be at least suffix_length");
- assert!(!self.mask.is_trie() || suffix_length <= MAX_TRIE_SUFFIX, "trie suffix is too long");
-
- let head_dim = self.head_dim;
- AttnParams {
- q_strides: [0, suffix_length * head_dim, head_dim],
- k_strides: [0, head_dim, self.num_groups * head_dim],
- v_strides: [0, head_dim, self.num_groups * head_dim],
- o_strides: [0, head_dim, self.num_q_heads * head_dim],
- gqa_factor: self.num_q_heads / self.num_groups,
- scale: self.scale.unwrap_or(1.0f32 / (head_dim as f32).sqrt()),
- q_len: suffix_length,
- k_len: kv_length,
- q_off: kv_length - suffix_length,
- nq_aligned: 0,
- q_rem: 0,
- nk: kv_length.div_ceil(self.block_k),
- nk_aligned: kv_length / self.block_k,
- k_rem: kv_length % self.block_k,
- }
- }
-}
-
-pub struct AttentionGemmGrouped {
- variants: Mutex<HashMap<(MaskKind, u32), AttentionGemmGroupedMetal>>,
- config: AttentionKernelConfig,
-}
-
-impl AttentionGemmGrouped {
- fn get_or_create(
- &self,
- context: &MetalContext,
- mask: MaskKind,
- head_dim_slices: u32,
- ) -> Result<MappedMutexGuard<'_, AttentionGemmGroupedMetal>, MetalError> {
- let key = (mask, head_dim_slices);
- let mut variants = self.variants.lock();
- if let Entry::Vacant(slot) = variants.entry(key) {
- slot.insert(AttentionGemmGroupedMetal::new_fixed(context, &self.config, head_dim_slices, mask)?);
- }
- Ok(MutexGuard::map(variants, |variants| {
- variants.get_mut(&key).expect("attention variant was just initialized")
- }))
- }
-
- pub fn is_supported(config: &AttentionKernelConfig) -> bool {
- policy::is_supported(config)
- }
-
- pub fn new(config: &AttentionKernelConfig) -> Self {
- Self {
- variants: Mutex::new(HashMap::new()),
- config: *config,
- }
- }
-
- pub fn should_encode(
- &self,
- mask: MaskKind,
- suffix_length: u32,
- kv_length: u32,
- use_mxu: bool,
- ) -> bool {
- let slices = policy::select_head_dim_slices(self.config.head_dim, mask, suffix_length, kv_length, use_mxu);
- slices.is_some_and(|slices| slices != 1 || self.config.num_q_heads == self.config.num_groups * 4)
- }
-
- pub fn encode(
- &self,
- mask: MaskKind,
- input: FullPrecisionInput<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<(<Metal as Backend>::ScratchBuffer, bool), MetalError> {
- let suffix_length = arguments.suffix_length;
- assert!(arguments.cache.ring_params().is_none(), "ring KV cache is unsupported");
- assert!(arguments.sinks.is_none(), "attention sinks are unsupported");
-
- let kv_length = arguments.cache.prefix_len() + suffix_length;
- let head_dim_slices = policy::select_head_dim_slices(
- self.config.head_dim,
- mask,
- suffix_length,
- kv_length,
- command_buffer.context().supports_mxu,
- )
- .expect("grouped attention request must be supported");
- assert!(head_dim_slices != 1 || self.config.num_q_heads == self.config.num_groups * 4);
- let mut output = command_buffer.allocate_scratch_for_shape(
- &[suffix_length, self.config.num_q_heads, self.config.head_dim],
- DataType::BF16,
- )?;
- let gpu_core_count = command_buffer.context().gpu_core_count;
- let core = self.get_or_create(command_buffer.context(), mask, head_dim_slices)?;
- let geometry = SplitGeometry {
- head_dim: core.head_dim,
- num_q_heads: core.num_q_heads,
- num_groups: core.num_groups,
- query_rows_per_threadgroup: core.query_rows_per_threadgroup,
- block_k: core.block_k,
- };
- let num_splits =
- choose_splits(geometry, suffix_length, kv_length, gpu_core_count, command_buffer.context().supports_mxu);
- let gate_applied = core.encode(
- input.queries,
- input.keys,
- input.values,
- &mut output,
- arguments.trie,
- arguments.gate,
- suffix_length,
- kv_length,
- num_splits,
- command_buffer,
- )?;
- Ok((output, gate_applied))
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs
deleted file mode 100644
index 8a0395ce0..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs
+++ /dev/null
@@ -1,192 +0,0 @@
-use super::MaskKind;
-use crate::{
- backends::common::{gpu_types::kv_layout, kernel::AttentionKernelConfig},
- data_type::DataType,
-};
-
-pub const MAX_TRIE_SUFFIX: u32 = 64;
-
-const MXU_DECODE_MAX_SUFFIX: u32 = 64;
-const SHORT_SUFFIX_MAX: u32 = 4;
-
-pub fn is_supported(arguments: &AttentionKernelConfig) -> bool {
- matches!(arguments.head_dim, 128 | 256)
- && arguments.data_type == DataType::BF16
- && !arguments.has_sinks
- && !arguments.is_kv_cache_ring
- && arguments.sliding_window_size.is_none()
- && arguments.scale.is_none_or(|scale| scale > 0.0)
- && arguments.num_groups > 0
- && arguments.num_q_heads > 0
- && arguments.num_q_heads.is_multiple_of(arguments.num_groups)
-}
-
-pub fn select_head_dim_slices(
- head_dim: u32,
- mask: MaskKind,
- suffix_length: u32,
- kv_length: u32,
- use_mxu: bool,
-) -> Option<u32> {
- const SIMDGROUP_DECODE_MIN_KV_LENGTH: u32 = 16_384;
- const SIMDGROUP_PREFILL_MIN_KV_LENGTH: u32 = 61_440;
-
- match (use_mxu, mask, head_dim, suffix_length) {
- (true, _, _, 2..=64) => Some(head_dim / kv_layout::SLICE_DIMS),
- (true, MaskKind::Causal, 256, 65..=1024) => Some(4),
- (false, MaskKind::Causal, 256, 1 | 2 | 4) if kv_length >= SIMDGROUP_DECODE_MIN_KV_LENGTH => {
- Some(8 / suffix_length)
- },
- (false, MaskKind::Causal, 128, 1 | 2 | 4) if kv_length >= SIMDGROUP_DECODE_MIN_KV_LENGTH => Some(4),
- (false, MaskKind::Causal, 128, 512 | 1024) if kv_length >= 30_720 => Some(1),
- (false, MaskKind::Causal, 256, 512 | 1024) if kv_length >= SIMDGROUP_PREFILL_MIN_KV_LENGTH => Some(2),
- _ => None,
- }
-}
-
-type MeasuredSplits = (u32, u32, &'static [(u32, u32)]);
-
-const MEASURED_SUFFIX_MIN: u32 = 2;
-const MEASURED_SUFFIX_MAX: u32 = 64;
-
-const MEASURED_TG_PER_CORE_TENTHS: &[MeasuredSplits] = &[
- (256, 16, &[(0, 24), (5120, 18), (131072, 39)]),
- (256, 32, &[(0, 24), (5120, 18), (32768, 60)]),
- (256, 64, &[(0, 24), (5120, 60)]),
- (128, 16, &[(0, 16), (51200, 40)]),
- (128, 32, &[(0, 16), (5120, 40), (51200, 80)]),
- (128, 64, &[(0, 32), (5120, 40), (32768, 80)]),
-];
-const TG_PER_CORE_FALLBACK: u32 = 6;
-const TENTHS_PER_RATIO: u32 = 10;
-const PREFILL_SPLIT_KEYS: u32 = 2048;
-const PREFILL_SPLIT_MIN_KV: u32 = 16384;
-const PREFILL_SPLIT_SCRATCH_BYTES: u64 = 256 << 20;
-const PREFILL_MIN_SPLITS: u32 = 2;
-const PARTIAL_STATS_PER_ROW: u64 = 2;
-
-fn partial_row_bytes(head_dim: u32) -> u64 {
- head_dim as u64 * DataType::BF16.size_in_bytes() as u64
- + PARTIAL_STATS_PER_ROW * DataType::F32.size_in_bytes() as u64
-}
-
-pub struct SplitGeometry {
- pub head_dim: u32,
- pub num_q_heads: u32,
- pub num_groups: u32,
- pub query_rows_per_threadgroup: u32,
- pub block_k: u32,
-}
-
-fn tg_per_core_tenths_for(
- steps: &[(u32, u32)],
- kv_length: u32,
-) -> u32 {
- steps.iter().rev().find(|(minimum_kv, _)| kv_length >= *minimum_kv).map_or(steps[0].1, |(_, tenths)| *tenths)
-}
-
-fn splits_for_ratio(
- tg_per_core_tenths: u32,
- gpu_core_count: u32,
- threadgroups_per_kv_split: u32,
-) -> u32 {
- (tg_per_core_tenths * gpu_core_count.max(1)).div_ceil(TENTHS_PER_RATIO * threadgroups_per_kv_split.max(1))
-}
-
-fn tabled_splits(
- head_dim: u32,
- suffix_length: u32,
- kv_length: u32,
- threadgroups_per_kv_split: u32,
- gpu_core_count: u32,
-) -> Option<u32> {
- if !(MEASURED_SUFFIX_MIN..=MEASURED_SUFFIX_MAX).contains(&suffix_length) {
- return None;
- }
- MEASURED_TG_PER_CORE_TENTHS
- .iter()
- .filter(|(row_head_dim, _, _)| *row_head_dim == head_dim)
- .min_by_key(|(_, row_suffix, _)| (row_suffix.abs_diff(suffix_length), u32::MAX - row_suffix))
- .map(|(_, _, steps)| {
- splits_for_ratio(tg_per_core_tenths_for(steps, kv_length), gpu_core_count, threadgroups_per_kv_split)
- })
-}
-
-pub fn choose_splits(
- geometry: SplitGeometry,
- suffix_length: u32,
- kv_length: u32,
- gpu_core_count: u32,
- use_mxu: bool,
-) -> u32 {
- let threadgroups_per_kv_split = (geometry.num_q_heads / geometry.num_groups * suffix_length)
- .div_ceil(geometry.query_rows_per_threadgroup)
- * geometry.num_groups;
- let max_splits = kv_length.div_ceil(geometry.block_k).max(1);
-
- if !use_mxu {
- const MAX_SPLITS: u32 = 16;
- let threadgroups_per_split = threadgroups_per_kv_split.max(1);
- let splits = if suffix_length > SHORT_SUFFIX_MAX {
- let bytes_per_split = threadgroups_per_split as u64
- * geometry.query_rows_per_threadgroup as u64
- * partial_row_bytes(geometry.head_dim);
- (PREFILL_SPLIT_SCRATCH_BYTES / bytes_per_split) as u32
- } else {
- (gpu_core_count.max(1) * 4).div_ceil(threadgroups_per_split)
- };
- return splits.clamp(1, max_splits.min(MAX_SPLITS));
- }
-
- if suffix_length > MXU_DECODE_MAX_SUFFIX && kv_length >= PREFILL_SPLIT_MIN_KV {
- let f32_estimated_bytes_per_split = threadgroups_per_kv_split as u64
- * geometry.query_rows_per_threadgroup as u64
- * (geometry.head_dim as u64 + PARTIAL_STATS_PER_ROW)
- * DataType::F32.size_in_bytes() as u64;
- let requested_splits = kv_length.div_ceil(PREFILL_SPLIT_KEYS).min(max_splits);
- let scratch_splits = PREFILL_SPLIT_SCRATCH_BYTES / f32_estimated_bytes_per_split;
- let splits = (requested_splits as u64).min(scratch_splits) as u32;
- if splits >= PREFILL_MIN_SPLITS {
- return splits;
- }
- }
-
- let measured_splits =
- tabled_splits(geometry.head_dim, suffix_length, kv_length, threadgroups_per_kv_split, gpu_core_count);
- let splits = match measured_splits {
- Some(splits) => splits,
- None => splits_for_ratio(TENTHS_PER_RATIO * TG_PER_CORE_FALLBACK, gpu_core_count, threadgroups_per_kv_split),
- };
- splits.clamp(1, max_splits)
-}
-
-pub fn int8_splits(
- split_rows: u32,
- head_dim: u32,
- suffix_length: u32,
- kv_length: u32,
-) -> u32 {
- const SHORT_SUFFIX_MAX_SPLITS: u32 = 16;
- let kv_blocks = kv_length.div_ceil(kv_layout::TILE_KEYS);
- let splits = if suffix_length <= MXU_DECODE_MAX_SUFFIX {
- let query_tokens = suffix_length.max(kv_layout::TILE_QUERIES);
- let splits = (kv_length as f32 / query_tokens as f32).sqrt().round() as u32;
- if suffix_length <= SHORT_SUFFIX_MAX {
- splits.min(SHORT_SUFFIX_MAX_SPLITS)
- } else {
- splits
- }
- } else if kv_length >= PREFILL_SPLIT_MIN_KV {
- let bytes_per_split = split_rows as u64 * partial_row_bytes(head_dim);
- let scratch_splits = (PREFILL_SPLIT_SCRATCH_BYTES / bytes_per_split) as u32;
- let rounded_splits = (kv_length + PREFILL_SPLIT_KEYS / 2) / PREFILL_SPLIT_KEYS;
- rounded_splits.min(scratch_splits)
- } else {
- 1
- };
- splits.clamp(1, kv_blocks.max(1))
-}
-
-#[cfg(test)]
-#[path = "../../../../../../unit/backends/metal/kernel/attention/gemm_grouped_policy_test.rs"]
-mod tests;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/int8/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/int8/mod.rs
deleted file mode 100644
index 344c86200..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/int8/mod.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use super::gemm_grouped::{
- policy::{self, MAX_TRIE_SUFFIX, int8_splits},
- query_rows_per_threadgroup,
-};
-use crate::{
- backends::{
- common::{
- Backend, BufferMut, BufferRef, CommandBufferEncoding,
- gpu_types::kv_layout,
- kernel::{AttentionArguments, AttentionKernelConfig, Int8Input},
- },
- metal::{
- Metal,
- command_buffer::MetalCommandBufferEncoding,
- context::MetalContext,
- error::MetalError,
- gpu_types::attention::AttnParams,
- kernel::{AttentionGemmGroupedInt8CombineMetalKernel, AttentionGemmGroupedInt8MetalKernel},
- },
- },
- data_type::DataType,
-};
-
-pub struct Int8Attention {
- config: AttentionKernelConfig,
- mask_free: AttentionGemmGroupedInt8MetalKernel,
- masked: AttentionGemmGroupedInt8MetalKernel,
- trie: AttentionGemmGroupedInt8MetalKernel,
- combine: AttentionGemmGroupedInt8CombineMetalKernel,
-}
-
-impl Int8Attention {
- pub fn is_supported(
- config: &AttentionKernelConfig,
- context: &MetalContext,
- ) -> bool {
- policy::is_supported(config) && context.supports_mxu && config.is_causal
- }
-
- pub fn new(
- context: &MetalContext,
- config: &AttentionKernelConfig,
- ) -> Result<Self, MetalError> {
- let kernel = |mask_free, is_trie| {
- AttentionGemmGroupedInt8MetalKernel::new(
- context,
- DataType::BF16,
- config.head_dim,
- mask_free,
- is_trie,
- config.num_groups,
- )
- };
- Ok(Self {
- config: *config,
- mask_free: kernel(true, false)?,
- masked: kernel(false, false)?,
- trie: kernel(false, true)?,
- combine: AttentionGemmGroupedInt8CombineMetalKernel::new(
- context,
- DataType::BF16,
- config.head_dim,
- config.gate_row_stride.is_some(),
- )?,
- })
- }
-
- pub fn encode(
- &self,
- input: Int8Input<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
- let AttentionArguments {
- suffix_length,
- trie,
- cache,
- gate,
- ..
- } = arguments;
- let config = &self.config;
- let (head_dim, num_q_heads, num_groups) = (config.head_dim, config.num_q_heads, config.num_groups);
- assert!(trie.is_none() || suffix_length <= MAX_TRIE_SUFFIX, "trie suffix is not supported");
- let prefix_len = cache.prefix_len();
- let kv_length = prefix_len + suffix_length;
-
- let gqa_factor = num_q_heads / num_groups;
- let grouped_rows = gqa_factor * suffix_length;
- let query_rows_per_threadgroup = query_rows_per_threadgroup(head_dim);
- let query_tiles = grouped_rows.div_ceil(query_rows_per_threadgroup);
- let split_rows = num_groups * query_tiles * query_rows_per_threadgroup;
- let num_splits = int8_splits(split_rows, head_dim, suffix_length, kv_length);
-
- let rows = split_rows * num_splits;
- let mut partials = command_buffer.allocate_scratch_for_shape(&[rows, head_dim], DataType::BF16)?;
- let mut partial_maxs = command_buffer.allocate_scratch_for_shape(&[rows], DataType::F32)?;
- let mut partial_sums = command_buffer.allocate_scratch_for_shape(&[rows], DataType::F32)?;
- let params = AttnParams {
- q_strides: [0, grouped_rows * head_dim, head_dim],
- k_strides: [0, head_dim, num_groups * head_dim],
- v_strides: [0, head_dim, num_groups * head_dim],
- o_strides: [0, head_dim, num_q_heads * head_dim],
- gqa_factor,
- scale: config.scale.unwrap_or(1.0 / (head_dim as f32).sqrt()),
- q_len: suffix_length,
- k_len: kv_length,
- q_off: prefix_len,
- nk: kv_length.div_ceil(kv_layout::TILE_KEYS),
- nk_aligned: kv_length / kv_layout::TILE_KEYS,
- k_rem: kv_length % kv_layout::TILE_KEYS,
- ..AttnParams::default()
- };
- let prefix_splits = (0..num_splits)
- .take_while(|split| ((split + 1) * params.nk / num_splits) * kv_layout::TILE_KEYS <= params.q_off)
- .count() as u32;
- let mut dispatch = |kernel: &AttentionGemmGroupedInt8MetalKernel, trie, split_base: u32, split_count: u32| {
- let split_byte_range = |row_bytes: usize| {
- let split_bytes = split_rows as usize * row_bytes;
- split_base as usize * split_bytes..(split_base + split_count) as usize * split_bytes
- };
- kernel.encode(
- input.query_codes,
- input.query_scales,
- input.k_codes,
- input.k_scales,
- input.v_codes,
- input.v_scales,
- trie,
- (&mut partials).subrange_mut(split_byte_range(head_dim as usize * DataType::BF16.size_in_bytes())),
- (&mut partial_maxs).subrange_mut(split_byte_range(DataType::F32.size_in_bytes())),
- (&mut partial_sums).subrange_mut(split_byte_range(DataType::F32.size_in_bytes())),
- params,
- query_tiles,
- num_splits,
- split_base,
- split_count,
- suffix_length,
- command_buffer,
- )
- };
- if prefix_splits > 0 {
- dispatch(&self.mask_free, None, 0, prefix_splits);
- }
- dispatch(trie.map_or(&self.masked, |_| &self.trie), trie, prefix_splits, num_splits - prefix_splits);
-
- let mut output =
- command_buffer.allocate_scratch_for_shape(&[suffix_length, num_q_heads, head_dim], DataType::BF16)?;
- self.combine.encode(
- &partials,
- &partial_maxs,
- &partial_sums,
- &mut output,
- gate,
- params,
- grouped_rows,
- query_tiles * query_rows_per_threadgroup,
- num_groups,
- num_splits,
- config.gate_row_stride,
- command_buffer,
- );
- Ok(output)
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/int8_quantization.h b/crates/uzu-engine/src/backends/metal/kernel/attention/int8_quantization.h
new file mode 100644
index 000000000..8acb3ba40
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/int8_quantization.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <metal_stdlib>
+#include "../common/defines.h"
+
+UZU_CONST float INT8_MAX = 127.0f;
+
+template <ushort VALUES_PER_LANE>
+METAL_FUNC bfloat kv_quantize_row(const thread float* values, thread int* codes) {
+ float abs_max = 0.0f;
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ abs_max = metal::max(abs_max, metal::abs(values[value_index]));
+ }
+ abs_max = metal::simd_max(abs_max);
+ const bfloat scale = bfloat(abs_max > 0.0f ? metal::precise::divide(abs_max, INT8_MAX) : 1.0f);
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ codes[value_index] =
+ int(metal::clamp(metal::rint(metal::precise::divide(values[value_index], float(scale))), -INT8_MAX, INT8_MAX));
+ }
+ return scale;
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/kv_cache_update.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/kv_cache_update.metal
index 2360ee8b8..ef7eacf82 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/kv_cache_update.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/kv_cache_update.metal
@@ -6,26 +6,7 @@
namespace kv_layout = uzu::kv_layout;
-template <typename T>
-VARIANTS(T, bfloat)
-PUBLIC KERNEL(KVCacheUpdate) (
- device T* in_place_keys,
- device T* in_place_values,
- const constant uzu::kv_cache_update::Copy* copies,
- const constant uint& copy_count,
- const constant uint& element_dim,
- const uint element_idx AXIS(element_dim, 256)
-) {
- for (uint i = 0; i < copy_count; ++i) {
- const uint sourceIdx = copies[i].source * element_dim + element_idx;
- const uint destIdx = copies[i].destination * element_dim + element_idx;
-
- in_place_keys[destIdx] = in_place_keys[sourceIdx];
- in_place_values[destIdx] = in_place_values[sourceIdx];
- }
-}
-
-PUBLIC KERNEL(KVCacheUpdateInt8)(
+PUBLIC KERNEL(KVCacheUpdate)(
device int8_t* in_place_k_codes,
device uchar* in_place_v_codes,
device bfloat* in_place_k_scales,
@@ -34,9 +15,10 @@ PUBLIC KERNEL(KVCacheUpdateInt8)(
const constant uint& copy_count,
const uint head_dim SPECIALIZE,
const uint num_kv_heads SPECIALIZE,
+ const uint32_t backend_opaque_layout SPECIALIZE,
const uint element AXIS(num_kv_heads* head_dim, 256)
) {
- const kv_layout::Int8KVShape shape{head_dim, num_kv_heads};
+ const kv_layout::KVShape shape{head_dim, num_kv_heads, static_cast<kv_layout::KVLayout>(backend_opaque_layout)};
const uint kv_head = element / head_dim;
const uint channel = element % head_dim;
for (uint i = 0; i < copy_count; ++i) {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/kv_layout.h b/crates/uzu-engine/src/backends/metal/kernel/attention/kv_layout.h
index b103146d4..1aa568f52 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/kv_layout.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/kv_layout.h
@@ -4,9 +4,6 @@
#include "../common/defines.h"
#include "../generated/kv_layout.h"
-// K: [block][head][fragment][lane][LANE_BYTES].
-// V: [block][head][slice][chunk group][lane][LANE_BYTES].
-
namespace uzu::kv_layout {
// Lane bits: row[2], group[1], row[1], row[0], group[0].
@@ -15,20 +12,24 @@ METAL_FUNC uint mma_lane(const uint row_in_group, const uint channel_group) {
((row_in_group & 1u) << 1) | (channel_group & 1u);
}
-struct Int8KVShape {
+struct KVShape {
uint head_dim;
uint num_kv_heads;
+ KVLayout layout;
METAL_FUNC size_t block_region(const uint block, const uint kv_head) const {
return (size_t(block) * num_kv_heads + kv_head) * (kv_layout::TILE_KEYS * head_dim);
}
- METAL_FUNC size_t scale_index(const uint key, const uint kv_head) const {
- return (size_t(key / kv_layout::TILE_KEYS) * num_kv_heads + kv_head) * kv_layout::TILE_KEYS +
- key % kv_layout::TILE_KEYS;
+ // Scales: [key block][head][key in block].
+ METAL_FUNC uint scale_index(const uint key, const uint kv_head) const {
+ return (key / kv_layout::TILE_KEYS * num_kv_heads + kv_head) * kv_layout::TILE_KEYS + key % kv_layout::TILE_KEYS;
}
METAL_FUNC size_t k_code_index(const uint key, const uint kv_head, const uint channel) const {
+ if (layout == KVLayout::RowMajor)
+ return size_t(scale_index(key, kv_head)) * head_dim + channel;
+ // K: [block][head][fragment][lane][LANE_BYTES].
const uint row = key % kv_layout::TILE_KEYS;
const uint lane = mma_lane(row % kv_layout::GROUP_ROWS, channel % kv_layout::TILE_DIMS / kv_layout::LANE_COLS);
const uint lane_offset = row / kv_layout::GROUP_ROWS * kv_layout::LANE_COLS + channel % kv_layout::LANE_COLS;
@@ -37,6 +38,9 @@ struct Int8KVShape {
}
METAL_FUNC size_t v_code_index(const uint key, const uint kv_head, const uint channel) const {
+ if (layout == KVLayout::RowMajor)
+ return k_code_index(key, kv_head, channel);
+ // V: [block][head][slice][chunk group][lane][LANE_BYTES].
const uint row = key % kv_layout::TILE_KEYS;
const uint slice_channel = channel % kv_layout::SLICE_DIMS;
const uint tile = slice_channel / kv_layout::TILE_DIMS;
@@ -54,7 +58,7 @@ struct Int8KVShape {
};
METAL_FUNC float rotation_sign(const uint channel) {
- const uint word = kv_layout::ROTATION_SIGN_BITS[channel / kv_layout::WORD_BITS];
+ const uint word = kv_layout::ROTATION_SIGN_BITS[(channel / kv_layout::WORD_BITS) % 8];
const uint bit = channel % kv_layout::WORD_BITS;
return (word >> bit) & 1u ? -1.0f : 1.0f;
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/matrix.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix.metal
new file mode 100644
index 000000000..2bfd97d38
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix.metal
@@ -0,0 +1,115 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+#include "../common/thread_context.h"
+#include "../generated/attention.h"
+#include "../generated/trie.h"
+#include "matrix_layout.h"
+#include "matrix_mxu.h"
+#include "matrix_simd.h"
+
+using namespace metal;
+
+template <typename ScaleType, uint HEAD_DIM, bool USE_MXU, uint NUM_SIMDGROUPS>
+VARIANTS(ScaleType, bfloat)
+VARIANTS(HEAD_DIM, 64, 128, 256, 512)
+VARIANTS(USE_MXU, false, true)
+VARIANTS(NUM_SIMDGROUPS, 1, 2, 4, 6, 8)
+CONSTRAINT(!USE_MXU || NUM_SIMDGROUPS % (HEAD_DIM / 64) == 0)
+CONSTRAINT(HEAD_DIM != 256 || NUM_SIMDGROUPS % 2 == 0)
+CONSTRAINT(HEAD_DIM != 512 || NUM_SIMDGROUPS % 4 == 0)
+KERNEL(AttentionMatrix)(
+ const device int8_t* query_codes,
+ const device ScaleType* query_scales,
+ const device int8_t* key_codes,
+ const device ScaleType* key_scales,
+ const device uchar* value_codes,
+ const device ScaleType* value_scales,
+ const device uzu::trie::TrieNode* trie OPTIONAL(is_trie),
+ const constant uzu::ring::RingParams& ring_params OPTIONAL(is_kv_cache_ring),
+ const constant uint& sliding_window_size OPTIONAL(is_sliding_window),
+ device bfloat* partial_values,
+ device float* partial_maxima,
+ device float* partial_denominators,
+ const constant uzu::attention::AttnParams& params,
+ const constant uint& query_tiles,
+ const constant uint& num_splits,
+ const constant uint& split_base,
+ const constant uint& split_count,
+ const constant uint& trie_nodes,
+ const bool is_causal SPECIALIZE,
+ const bool is_kv_cache_ring SPECIALIZE,
+ const bool is_sliding_window SPECIALIZE,
+ const bool mask_free SPECIALIZE,
+ const bool is_trie SPECIALIZE,
+ const uint32_t num_kv_heads SPECIALIZE,
+ threadgroup float probability_exchange[AttentionMatrixScratch<HEAD_DIM, USE_MXU, NUM_SIMDGROUPS>::EXCHANGE_FLOATS],
+ threadgroup ulong row_masks[AttentionMatrixScratch<HEAD_DIM, USE_MXU, NUM_SIMDGROUPS>::ROW_MASKS],
+ threadgroup uint4 query_stage[AttentionMatrixScratch<HEAD_DIM, USE_MXU, NUM_SIMDGROUPS>::STAGING_VECTORS],
+ const ThreadContext thread_context,
+ const uint tile_split_index GROUPS(query_tiles * split_count),
+ const uint kv_head_index GROUPS(num_kv_heads),
+ const uint thread_index THREADS(NUM_SIMDGROUPS * METAL_SIMD_SIZE)
+) {
+ if constexpr (USE_MXU) {
+ attention_matrix_mxu<ScaleType, HEAD_DIM, NUM_SIMDGROUPS>(
+ query_codes,
+ query_scales,
+ key_codes,
+ key_scales,
+ value_codes,
+ value_scales,
+ trie,
+ ring_params,
+ sliding_window_size,
+ is_causal,
+ is_kv_cache_ring,
+ is_sliding_window,
+ partial_values,
+ partial_maxima,
+ partial_denominators,
+ params,
+ query_tiles,
+ num_splits,
+ split_base,
+ trie_nodes,
+ mask_free,
+ is_trie,
+ num_kv_heads,
+ probability_exchange,
+ row_masks,
+ query_stage,
+ thread_context,
+ tile_split_index,
+ kv_head_index
+ );
+ } else {
+ attention_matrix_simd<ScaleType, HEAD_DIM, NUM_SIMDGROUPS>(
+ query_codes,
+ query_scales,
+ key_codes,
+ key_scales,
+ value_codes,
+ value_scales,
+ trie,
+ ring_params,
+ sliding_window_size,
+ is_causal,
+ is_kv_cache_ring,
+ is_sliding_window,
+ partial_values,
+ partial_maxima,
+ partial_denominators,
+ params,
+ query_tiles,
+ num_splits,
+ trie_nodes,
+ is_trie,
+ num_kv_heads,
+ probability_exchange,
+ reinterpret_cast<threadgroup half*>(query_stage),
+ thread_context,
+ tile_split_index,
+ kv_head_index
+ );
+ }
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine_int8.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_combine.metal
similarity index 88%
rename from crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine_int8.metal
rename to crates/uzu-engine/src/backends/metal/kernel/attention/matrix_combine.metal
index db1e7c23f..dc945a949 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine_int8.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_combine.metal
@@ -1,21 +1,22 @@
#include <metal_stdlib>
-#include "../../common/dsl.h"
-#include "../../generated/attention.h"
-#include "../../hadamard_transform/hadamard_transform.h"
-#include "../../common/sigmoid_gate.h"
-#include "../kv_layout.h"
+#include "../common/dsl.h"
+#include "../generated/attention.h"
+#include "../hadamard_transform/hadamard_transform.h"
+#include "../common/sigmoid_gate.h"
+#include "kv_layout.h"
using namespace metal;
template <typename T, uint BD>
-VARIANTS(T, bfloat)
-VARIANTS(BD, 128, 256)
-KERNEL(AttentionGemmGroupedInt8Combine)(
+VARIANTS(T, bfloat, float)
+VARIANTS(BD, 64, 128, 256, 512)
+KERNEL(AttentionMatrixCombine)(
const device bfloat* partials,
const device float* partial_maxs,
const device float* partial_sums,
device T* o,
const device T* gate OPTIONAL(has_gate),
+ const device T* sinks OPTIONAL(has_sinks),
const constant uzu::attention::AttnParams& params,
const constant uint& grouped_rows,
const constant uint& padded_rows,
@@ -23,6 +24,7 @@ KERNEL(AttentionGemmGroupedInt8Combine)(
const constant uint& num_splits,
const constant uint& gate_row_stride OPTIONAL(has_gate),
const bool has_gate SPECIALIZE,
+ const bool has_sinks SPECIALIZE,
threadgroup float rotation[BD],
const uint grouped_row_idx GROUPS(grouped_rows),
const uint kv_head_idx GROUPS(kv_heads),
@@ -40,7 +42,8 @@ KERNEL(AttentionGemmGroupedInt8Combine)(
float numerator = 0.0f;
float denominator = 0.0f;
constexpr uint SIMDGROUPS = BD / METAL_SIMD_SIZE;
- float global_max = -metal::numeric_limits<float>::infinity();
+ const float sink = has_sinks ? float(sinks[q_head_idx]) * M_LOG2E_F : -INFINITY;
+ float global_max = sink;
for (uint s = column; s < num_splits; s += BD) {
if (row_sums[s * split_rows] > 0.0f) {
global_max = metal::max(global_max, row_maxs[s * split_rows]);
@@ -57,6 +60,7 @@ KERNEL(AttentionGemmGroupedInt8Combine)(
}
threadgroup_barrier(mem_flags::mem_threadgroup);
+ denominator = has_sinks ? fast::exp2(sink - global_max) : 0.0f;
threadgroup float* split_weights = rotation;
for (uint chunk_start = 0; chunk_start < num_splits; chunk_start += BD) {
const uint split = chunk_start + column;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_layout.h b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_layout.h
new file mode 100644
index 000000000..ec62d310c
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_layout.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include <metal_stdlib>
+#include "../common/defines.h"
+#include "../common/dsl.h"
+#include "../generated/kv_layout.h"
+#include "../matmul/common/mxu_fragment/ops.h"
+#include "../matmul/common/simdgroup_fragment_ops.h"
+
+using namespace metal;
+
+#define ATTENTION_GQA_SIMDGROUPS 8
+
+template <uint BK, uint BD, uint HEAD_DIM_SLICES, bool USE_MXU = true, uint NUM_SIMDGROUPS = ATTENTION_GQA_SIMDGROUPS>
+struct AttentionMatrixLayout {
+ using Ops = metal::conditional_t<USE_MXU, uzu::matmul::MxuFragmentOps<>, uzu::matmul::SimdgroupFragmentOps>;
+
+ UZU_CONST int SIMDGROUPS = NUM_SIMDGROUPS;
+ UZU_CONST int TILE_ROWS = Ops::FRAGMENT_ROWS;
+ UZU_CONST int SLICE_COLS = int(BD) / int(HEAD_DIM_SLICES);
+ UZU_CONST int BANDS = SIMDGROUPS / int(HEAD_DIM_SLICES);
+ UZU_CONST int BLOCK_ROWS = BANDS * TILE_ROWS;
+ UZU_CONST int SCORE_TILE_ELEMENTS = TILE_ROWS * int(BK);
+};
+
+template <uint HEAD_DIM, bool USE_MXU = true, uint NUM_SIMDGROUPS = ATTENTION_GQA_SIMDGROUPS>
+struct AttentionMatrixScratch {
+ using Layout = AttentionMatrixLayout<
+ uzu::kv_layout::TILE_KEYS,
+ HEAD_DIM,
+ HEAD_DIM / uzu::kv_layout::SLICE_DIMS,
+ true,
+ NUM_SIMDGROUPS>;
+
+ // Exchange offsets are in floats.
+ UZU_CONST int STATS_OFFSET = Layout::SIMDGROUPS * Layout::SCORE_TILE_ELEMENTS / int(sizeof(float));
+ UZU_CONST int SUMS_OFFSET = STATS_OFFSET + Layout::SIMDGROUPS * Layout::TILE_ROWS * 2;
+ UZU_CONST int SLOT_FLOATS = SUMS_OFFSET + Layout::SIMDGROUPS * Layout::TILE_ROWS;
+ UZU_CONST int ROW_MASKS = USE_MXU ? Layout::BLOCK_ROWS : 1;
+
+ UZU_CONST int QUERY_VECTORS_PER_BAND = int(HEAD_DIM) / (2 * uzu::kv_layout::TILE_DIMS) * METAL_SIMD_SIZE;
+ UZU_CONST int QUERY_VECTORS = Layout::BANDS * QUERY_VECTORS_PER_BAND;
+ UZU_CONST int EXCHANGE_FLOATS = USE_MXU ? 2 * SLOT_FLOATS : NUM_SIMDGROUPS * 8 * (HEAD_DIM == 512 ? 16 : 32);
+ UZU_CONST int STAGING_VECTORS = USE_MXU ? QUERY_VECTORS : (HEAD_DIM == 512 ? 16 : 32) * (HEAD_DIM + 8) / 8;
+};
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_int8.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_mxu.h
similarity index 78%
rename from crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_int8.metal
rename to crates/uzu-engine/src/backends/metal/kernel/attention/matrix_mxu.h
index 1875a3f08..0491daba5 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_int8.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_mxu.h
@@ -1,29 +1,15 @@
-#include <metal_stdlib>
-#include "../../common/dsl.h"
-#include "../../common/conversion.h"
-#include "../../common/thread_context.h"
-#include "../../matmul/common/fragment.h"
-#include "../../generated/attention.h"
-#include "../../generated/trie.h"
-#include "../kv_layout.h"
-#include "layout.h"
-
-using namespace metal;
-using namespace uzu::matmul;
-
-template <uint HEAD_DIM>
-struct Int8Scratch {
- using Layout = AttentionGemmGroupedLayout<uzu::kv_layout::TILE_KEYS, HEAD_DIM, HEAD_DIM / uzu::kv_layout::SLICE_DIMS>;
+#pragma once
- // Exchange offsets are in floats.
- UZU_CONST int STATS_OFFSET = Layout::SIMDGROUPS * Layout::SCORE_TILE_ELEMENTS / int(sizeof(float));
- UZU_CONST int SUMS_OFFSET = STATS_OFFSET + Layout::SIMDGROUPS * Layout::TILE_ROWS * 2;
- UZU_CONST int SLOT_FLOATS = SUMS_OFFSET + Layout::SIMDGROUPS * Layout::TILE_ROWS;
- UZU_CONST int ROW_MASKS = Layout::BLOCK_ROWS;
+#include "../common/conversion.h"
+#include "../common/thread_context.h"
+#include "../generated/attention.h"
+#include "../generated/trie.h"
+#include "../matmul/common/fragment.h"
+#include "kv_layout.h"
+#include "mask.h"
+#include "matrix_layout.h"
- UZU_CONST int QUERY_VECTORS_PER_BAND = int(HEAD_DIM) / (2 * uzu::kv_layout::TILE_DIMS) * METAL_SIMD_SIZE;
- UZU_CONST int QUERY_VECTORS = Layout::BANDS * QUERY_VECTORS_PER_BAND;
-};
+using namespace uzu::matmul;
template <class Ops, int DEPTH_FRAGMENTS>
METAL_FUNC void prepare_queries(
@@ -60,7 +46,7 @@ METAL_FUNC void prepare_queries(
}
template <class OutputFragment>
-struct Int8Softmax {
+struct AttentionMatrixSoftmax {
using AccumType = typename OutputFragment::ElementType;
UZU_CONST int ROWS_PER_LANE = OutputFragment::FragmentOpsType::THREAD_ELEMENT_ROWS;
// Lazy rescale (FlashAttention-4): raise the running max only after an increase of 8 (2^8).
@@ -74,7 +60,7 @@ struct Int8Softmax {
AccumType denominator[ROWS_PER_LANE] = {};
AccumType value_bias[ROWS_PER_LANE] = {};
- METAL_FUNC Int8Softmax() { output.clear(); }
+ METAL_FUNC AttentionMatrixSoftmax() { output.clear(); }
METAL_FUNC void rescale(const threadgroup float4* slot_stats, uint blocks_in_step, uint stat_rows) thread {
AccumType step_max[ROWS_PER_LANE] = {running_max[0], running_max[1]};
@@ -112,39 +98,45 @@ struct Int8Softmax {
}
};
-template <typename ScaleType, uint HEAD_DIM>
-VARIANTS(ScaleType, bfloat)
-VARIANTS(HEAD_DIM, 128, 256)
-KERNEL(AttentionGemmGroupedInt8)(
+template <typename ScaleType, uint HEAD_DIM, uint NUM_SIMDGROUPS>
+METAL_FUNC void attention_matrix_mxu(
const device int8_t* query_codes,
const device ScaleType* query_scales,
const device int8_t* key_codes,
const device ScaleType* key_scales,
const device uchar* value_codes,
const device ScaleType* value_scales,
- const device uzu::trie::TrieNode* trie OPTIONAL(is_trie),
+ const device uzu::trie::TrieNode* trie,
+ const constant uzu::ring::RingParams& ring_params,
+ const constant uint& sliding_window_size,
+ bool is_causal,
+ bool is_kv_cache_ring,
+ bool is_sliding_window,
device bfloat* partial_values,
device float* partial_maxima,
device float* partial_denominators,
const constant uzu::attention::AttnParams& params,
- const constant uint& query_tiles,
- const constant uint& num_splits,
- const constant uint& split_base,
- const constant uint& split_count,
- const constant uint& trie_nodes,
- const bool mask_free SPECIALIZE,
- const bool is_trie SPECIALIZE,
- const uint32_t num_kv_heads SPECIALIZE,
- threadgroup float probability_exchange[2 * Int8Scratch<HEAD_DIM>::SLOT_FLOATS],
- threadgroup ulong row_masks[Int8Scratch<HEAD_DIM>::ROW_MASKS],
- threadgroup uint4 query_stage[Int8Scratch<HEAD_DIM>::QUERY_VECTORS],
- const ThreadContext thread_context,
- const uint tile_split_index GROUPS(query_tiles * split_count),
- const uint kv_head_index GROUPS(num_kv_heads),
- const uint thread_index THREADS(ATTENTION_GQA_SIMDGROUPS * METAL_SIMD_SIZE)
+ uint query_tiles,
+ uint num_splits,
+ uint split_base,
+ uint trie_nodes,
+ bool mask_free,
+ bool is_trie,
+ uint num_kv_heads,
+ threadgroup float* probability_exchange,
+ threadgroup ulong* row_masks,
+ threadgroup uint4* query_stage,
+ ThreadContext thread_context,
+ uint tile_split_index,
+ uint kv_head_index
) {
- using Layout = AttentionGemmGroupedLayout<uzu::kv_layout::TILE_KEYS, HEAD_DIM, HEAD_DIM / uzu::kv_layout::SLICE_DIMS>;
- using Scratch = Int8Scratch<HEAD_DIM>;
+ using Layout = AttentionMatrixLayout<
+ uzu::kv_layout::TILE_KEYS,
+ HEAD_DIM,
+ HEAD_DIM / uzu::kv_layout::SLICE_DIMS,
+ true,
+ NUM_SIMDGROUPS>;
+ using Scratch = AttentionMatrixScratch<HEAD_DIM, true, NUM_SIMDGROUPS>;
using Ops = typename Layout::Ops;
using AccumType = float;
@@ -189,7 +181,7 @@ KERNEL(AttentionGemmGroupedInt8)(
(size_t(uzu::kv_layout::TILE_KEYS) * (size_t(kv_head_index) * params.v_strides[1] + channel_offset)) +
size_t(lane) * uzu::kv_layout::LANE_BYTES;
- Int8Softmax<Fragment<AccumType, 1, VALUE_FRAGMENTS, Ops>> softmax;
+ AttentionMatrixSoftmax<Fragment<AccumType, 1, VALUE_FRAGMENTS, Ops>> softmax;
const uint prefix_length = params.q_off;
const uint key_length = params.k_len;
@@ -199,15 +191,22 @@ KERNEL(AttentionGemmGroupedInt8)(
uint(score_position.y) + uint(Ops::THREAD_ELEMENT_ROW_STRIDE)
};
const uint query_band_offset = uint(query_band) * uint(Layout::TILE_ROWS);
- if (!mask_free) {
+ const uint suffix_position = is_kv_cache_ring ? ring_params.ring_length : prefix_length;
+ uint query_positions[ROWS_PER_LANE];
+ uint logical_queries[ROWS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
+ query_positions[row] = (query_row_base + lane_rows[row]) % params.q_len;
+ logical_queries[row] =
+ is_sliding_window ? suffix_position + (is_trie ? trie[query_positions[row]].height : query_positions[row]) : 0u;
+ }
+ if (!mask_free && is_causal && !is_kv_cache_ring && !is_sliding_window) {
ulong row_mask[ROWS_PER_LANE];
- uint query_positions[ROWS_PER_LANE];
METAL_PRAGMA_UNROLL
for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
- query_positions[row] = (query_row_base + lane_rows[row]) % params.q_len;
row_mask[row] = is_trie ? 0ul : ulong(prefix_length + query_positions[row]);
}
- if (is_trie) {
+ if (is_trie && trie_nodes <= 64) {
for (uint node_index = 0; node_index < trie_nodes; ++node_index) {
const uzu::trie::TrieNode node = trie[node_index];
METAL_PRAGMA_UNROLL
@@ -235,12 +234,12 @@ KERNEL(AttentionGemmGroupedInt8)(
const uint last_query_position = (tile_first_row / params.q_len == tile_last_row / params.q_len)
? (tile_last_row % params.q_len)
: (params.q_len - 1u);
- const uint split_end_block = ((split_index + 1u) * params.nk) / num_splits;
- const uint end_block =
- min(split_end_block,
- (prefix_length + last_query_position + uint(uzu::kv_layout::TILE_KEYS)) / uint(uzu::kv_layout::TILE_KEYS));
+ const uint split_end = ((split_index + 1u) * params.nk) / num_splits;
+ const uint end_block = is_causal ? min(split_end,
+ (prefix_length + last_query_position + uint(uzu::kv_layout::TILE_KEYS)) /
+ uint(uzu::kv_layout::TILE_KEYS))
+ : split_end;
const uint block_count = end_block > first_block ? end_block - first_block : 0u;
- const bool has_tail_block = (params.k_rem != 0u) && (block_count > 0u) && (end_block == params.nk);
key_codes += size_t(first_block) * key_block_stride;
value_tiles += size_t(first_block) * value_block_stride;
@@ -249,8 +248,8 @@ KERNEL(AttentionGemmGroupedInt8)(
const AccumType log2_attention_scale = AccumType(params.scale) * AccumType(M_LOG2E_F);
const uint scales_per_block = uint(uzu::kv_layout::TILE_KEYS) * num_kv_heads;
- const size_t first_scale_index =
- uzu::kv_layout::Int8KVShape{HEAD_DIM, num_kv_heads}.scale_index(first_key, kv_head_index);
+ const size_t first_scale_index = uzu::kv_layout::KVShape{HEAD_DIM, num_kv_heads, uzu::kv_layout::KVLayout::MxuTiled}
+ .scale_index(first_key, kv_head_index);
const device ScaleType* block_key_scales = key_scales + first_scale_index;
const device ScaleType* block_value_scales = value_scales + first_scale_index;
@@ -283,11 +282,48 @@ KERNEL(AttentionGemmGroupedInt8)(
threadgroup float2* slot_sums,
threadgroup uchar* slot_codes) UZU_ALWAYS_INLINE {
const uint key_block = block_index + uint(channel_slice);
- const bool is_tail_block = has_tail_block && (key_block + 1u == block_count);
const uint key_base = first_key + key_block * uint(uzu::kv_layout::TILE_KEYS);
const device int8_t* block_keys = key_codes + key_block * key_block_stride;
ScoreFragment scores;
+ if (is_kv_cache_ring || is_sliding_window) {
+ bool any_visible = false;
+ scores.for_each_lane([&](ushort row, ushort column, thread AccumType& value) UZU_ALWAYS_INLINE {
+ const uint key = key_base + uint(score_position.x) +
+ uint(column / Ops::THREAD_ELEMENT_COLS) * Ops::FRAGMENT_COLS +
+ uint(column % Ops::THREAD_ELEMENT_COLS);
+ const bool visible = key < key_length && should_use_key(
+ ring_params,
+ trie,
+ sliding_window_size,
+ query_positions[row],
+ prefix_length,
+ suffix_position,
+ logical_queries[row],
+ key,
+ is_kv_cache_ring,
+ is_causal,
+ is_trie,
+ is_sliding_window
+ );
+ any_visible |= visible;
+ value = visible ? 0.0f : -INFINITY;
+ });
+ if (is_sliding_window && !simd_any(any_visible)) {
+ *reinterpret_cast<threadgroup uint4*>(slot_codes + uint(channel_slice) * uint(Layout::SCORE_TILE_ELEMENTS)) =
+ uint4(0);
+ if (score_position.x == 0) {
+ slot_stats[uint(channel_slice) * STAT_ROWS] = float4(
+ metal::numeric_limits<AccumType>::lowest(),
+ 0.0f,
+ metal::numeric_limits<AccumType>::lowest(),
+ 0.0f
+ );
+ slot_sums[uint(channel_slice) * STAT_ROWS] = float2(0);
+ }
+ return;
+ }
+ }
// Q x K^T (int8).
Fragment<int, 1, KEY_FRAGMENTS, Ops> score;
@@ -328,7 +364,11 @@ KERNEL(AttentionGemmGroupedInt8)(
for (int column = 0; column < Ops::THREAD_ELEMENT_COLS; ++column) {
const int lane_col = fragment_col * Ops::THREAD_ELEMENT_COLS + column;
const int scale_col = fragment_col * Ops::FRAGMENT_COLS + column;
- const bool valid = mask_free || key_base + uint(score_position.x) + uint(scale_col) < key_length;
+ const uint key = key_base + uint(score_position.x) + uint(scale_col);
+ const bool valid =
+ (mask_free || key < key_length) &&
+ (!is_kv_cache_ring || key >= prefix_length ||
+ (prefix_length + key - ring_params.ring_offset) % prefix_length < ring_params.ring_length);
key_scale_values[lane_col] = AccumType(lane_key_scales[scale_col]);
const float value_scale = float(lane_value_scales[scale_col]);
log2_value_scales[lane_col] = valid ? metal::precise::log2(value_scale) : 0.0f;
@@ -338,24 +378,37 @@ KERNEL(AttentionGemmGroupedInt8)(
}
scores.for_each_lane(
[&](ushort row, ushort column, thread AccumType& value, thread int& integer_score) UZU_ALWAYS_INLINE {
- value = metal::fma(
- AccumType(integer_score) * key_scale_values[column],
- query_score_scales[row],
- log2_value_scales[column]
- );
+ if ((!is_kv_cache_ring && !is_sliding_window) || value != -INFINITY) {
+ value = metal::fma(
+ AccumType(integer_score) * key_scale_values[column],
+ query_score_scales[row],
+ log2_value_scales[column]
+ );
+ }
},
score
);
- if (!mask_free && (is_tail_block || (key_base + uint(uzu::kv_layout::TILE_KEYS) > prefix_length))) {
+ if (!mask_free && !is_kv_cache_ring && !is_sliding_window &&
+ key_base + uint(uzu::kv_layout::TILE_KEYS) > prefix_length) {
scores.map_coords(lane, [&](short row, short column, AccumType value) UZU_ALWAYS_INLINE {
- const ulong row_mask = row_masks[query_band_offset + uint(row)];
const uint key = key_base + uint(column);
bool visible = key < key_length;
- if (is_trie) {
- visible = visible && (key < prefix_length || ((row_mask >> ulong(key - prefix_length)) & 1ul) != 0ul);
- } else {
- visible = visible && key <= uint(row_mask);
+ if (is_causal) {
+ const ulong row_mask = row_masks[query_band_offset + uint(row)];
+ if (is_trie) {
+ if (visible && key >= prefix_length) {
+ if (trie_nodes <= 64) {
+ visible = ((row_mask >> ulong(key - prefix_length)) & 1ul) != 0ul;
+ } else {
+ const auto node = trie[key - prefix_length];
+ const uint query = (query_row_base + uint(row)) % params.q_len;
+ visible = query >= node.trie_start && query <= node.trie_end;
+ }
+ }
+ } else {
+ visible = visible && key <= uint(row_mask);
+ }
}
return visible ? value : -metal::numeric_limits<AccumType>::infinity();
});
@@ -407,6 +460,9 @@ KERNEL(AttentionGemmGroupedInt8)(
const AccumType probability_code_sum[ROWS_PER_LANE] = {block_stats.y, block_stats.w};
const float2 block_sums = slot_sums[published_block * STAT_ROWS];
const AccumType denominator_sum[ROWS_PER_LANE] = {block_sums.x, block_sums.y};
+ if (is_sliding_window && simd_all(block_sums.x == 0.0f && block_sums.y == 0.0f)) {
+ continue;
+ }
AccumType block_weights[ROWS_PER_LANE];
METAL_PRAGMA_UNROLL
for (int row = 0; row < ROWS_PER_LANE; ++row) {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_simd.h b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_simd.h
new file mode 100644
index 000000000..4792d22d2
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/matrix_simd.h
@@ -0,0 +1,254 @@
+#pragma once
+
+#include "../matmul/common/fragment.h"
+#include "../matmul/common/simdgroup_fragment_ops.h"
+#include "kv_layout.h"
+#include "mask.h"
+#include "matrix_layout.h"
+
+using namespace uzu::matmul;
+
+template <uint HEAD_DIM, uint BK, bool IS_VALUE, uint NUM_SIMDGROUPS, typename Code, typename ScaleType>
+METAL_FUNC void stage_int8_tile(
+ const device Code* codes,
+ const device ScaleType* scales,
+ threadgroup half* tile,
+ uzu::kv_layout::KVShape shape,
+ uint key_base,
+ uint key_length,
+ uint kv_head,
+ uint thread_index
+) {
+ constexpr uint ROW_STRIDE = HEAD_DIM + 8;
+ constexpr uint VECTORS = BK * HEAD_DIM / 16;
+ const device uint4* rows = reinterpret_cast<const device uint4*>(codes + shape.k_code_index(key_base, kv_head, 0));
+ for (uint vector = thread_index; vector < VECTORS; vector += NUM_SIMDGROUPS * METAL_SIMD_SIZE) {
+ const uint row = vector / (HEAD_DIM / 16);
+ const uint channel = vector % (HEAD_DIM / 16) * 16;
+ const bool valid = key_base + row < key_length;
+ uint4 words = valid ? rows[vector] : uint4(0);
+ if constexpr (IS_VALUE)
+ words ^= uint4(0x80808080u);
+ // K/V/Q are staged as half after scaling (values stay far below 65504).
+ const float scale = valid ? float(scales[shape.scale_index(key_base + row, kv_head)]) : 0.0f;
+ METAL_PRAGMA_UNROLL
+ for (ushort chunk = 0; chunk < 4; ++chunk) {
+ const half4 values = half4(float4(as_type<char4>(words[chunk])) * scale);
+ *reinterpret_cast<threadgroup half4*>(tile + row * ROW_STRIDE + channel + chunk * 4) = values;
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+}
+
+template <typename ScaleType, uint HEAD_DIM, uint NUM_SIMDGROUPS>
+METAL_FUNC void attention_matrix_simd(
+ const device int8_t* query_codes,
+ const device ScaleType* query_scales,
+ const device int8_t* key_codes,
+ const device ScaleType* key_scales,
+ const device uchar* value_codes,
+ const device ScaleType* value_scales,
+ const device uzu::trie::TrieNode* trie,
+ const constant uzu::ring::RingParams& ring_params,
+ const constant uint& sliding_window_size,
+ bool is_causal,
+ bool is_kv_cache_ring,
+ bool is_sliding_window,
+ device bfloat* partial_values,
+ device float* partial_maxima,
+ device float* partial_denominators,
+ const constant uzu::attention::AttnParams& params,
+ uint query_tiles,
+ uint num_splits,
+ uint trie_nodes,
+ bool is_trie,
+ uint num_kv_heads,
+ threadgroup float* exchange,
+ threadgroup half* kv_tile,
+ ThreadContext thread_context,
+ uint tile_split_index,
+ uint kv_head_index
+) {
+ constexpr uint BK = HEAD_DIM == 512 ? 16 : 32;
+ constexpr uint SLICES = HEAD_DIM < 128 ? 1 : HEAD_DIM / 128;
+ constexpr uint BLOCK_ROWS = NUM_SIMDGROUPS / SLICES * 8;
+ using Layout = AttentionMatrixLayout<BK, HEAD_DIM, SLICES, false>;
+ using Ops = SimdgroupFragmentOps;
+ constexpr uint DEPTH_FRAGMENTS = Layout::SLICE_COLS / Ops::FRAGMENT_ROWS;
+ constexpr uint KEY_FRAGMENTS = BK / Ops::FRAGMENT_COLS;
+ constexpr uint VALUE_FRAGMENTS = Layout::SLICE_COLS / Ops::FRAGMENT_COLS;
+ using Query = Fragment<half, 1, 1, Ops>;
+ using Keys = Fragment<half, 1, KEY_FRAGMENTS, Ops, ReadTranspose>;
+ using Scores = Fragment<float, 1, KEY_FRAGMENTS, Ops>;
+ using Value = Fragment<half, 1, 1, Ops>;
+ using Output = Fragment<float, 1, VALUE_FRAGMENTS, Ops>;
+
+ const ushort lane = ushort(thread_context.simd_lane_id);
+ const uint simdgroup = thread_context.simdgroup_index;
+ const uint band = simdgroup / SLICES;
+ const uint slice = simdgroup % SLICES;
+ const uint query_tile = tile_split_index % query_tiles;
+ const uint split = tile_split_index / query_tiles;
+ const uint grouped_rows = params.gqa_factor * params.q_len;
+ const uint row_base = query_tile * BLOCK_ROWS + band * Ops::FRAGMENT_ROWS;
+ const uint channel_base = slice * Layout::SLICE_COLS;
+ const short2 position = Ops::get_position(lane);
+ const uint query_row = min(row_base + uint(position.y), grouped_rows - 1u);
+ const uint query_position = query_row % params.q_len;
+ const size_t query_group = size_t(kv_head_index) * grouped_rows;
+ const float query_scale = float(query_scales[query_group + query_row]) * params.scale * M_LOG2E_F;
+ const uzu::kv_layout::KVShape shape{HEAD_DIM, num_kv_heads, uzu::kv_layout::KVLayout::RowMajor};
+
+ Query queries[DEPTH_FRAGMENTS];
+ METAL_PRAGMA_UNROLL
+ for (ushort depth = 0; depth < DEPTH_FRAGMENTS; ++depth) {
+ queries[depth].clear();
+ queries[depth].map_coords(lane, [&](short row, short col, half) {
+ const uint q = min(row_base + uint(row), grouped_rows - 1u);
+ return half(
+ float(query_codes[(query_group + q) * HEAD_DIM + channel_base + depth * Ops::FRAGMENT_COLS + col]) *
+ query_scale
+ );
+ });
+ }
+
+ ulong trie_mask = 0ul;
+ if (is_trie) {
+ for (uint node_index = 0; node_index < min(trie_nodes, 64u); ++node_index) {
+ const auto node = trie[node_index];
+ if (query_position >= node.trie_start && query_position <= node.trie_end) {
+ trie_mask |= 1ul << node_index;
+ }
+ }
+ }
+
+ const uint num_blocks = (params.k_len + BK - 1) / BK;
+ const uint block_begin = split * num_blocks / num_splits;
+ const uint suffix_position = is_kv_cache_ring ? ring_params.ring_length : params.q_off;
+ const uint logical_query = suffix_position + (is_trie ? trie[query_position].height : query_position);
+ const uint tile_first = query_tile * BLOCK_ROWS;
+ const uint tile_last = min(tile_first + BLOCK_ROWS - 1u, grouped_rows - 1u);
+ const uint last_query =
+ tile_first / params.q_len == tile_last / params.q_len ? tile_last % params.q_len : params.q_len - 1u;
+ const uint block_end = is_causal ? min((split + 1u) * num_blocks / num_splits, (params.q_off + last_query + BK) / BK)
+ : (split + 1u) * num_blocks / num_splits;
+ Output output;
+ output.clear();
+ float running_max = -INFINITY;
+ float denominator = 0.0f;
+ threadgroup float* score_slot = exchange + simdgroup * Layout::SCORE_TILE_ELEMENTS;
+
+ for (uint block = block_begin; block < block_end; ++block) {
+ const uint key_base = block * BK;
+ stage_int8_tile<HEAD_DIM, BK, false, NUM_SIMDGROUPS>(
+ key_codes,
+ key_scales,
+ kv_tile,
+ shape,
+ key_base,
+ params.k_len,
+ kv_head_index,
+ simdgroup * METAL_SIMD_SIZE + lane
+ );
+ Scores scores;
+ scores.clear();
+ METAL_PRAGMA_UNROLL
+ for (ushort depth = 0; depth < DEPTH_FRAGMENTS; ++depth) {
+ Keys keys;
+ keys.load_from(lane, fragment_source(kv_tile + channel_base + depth * Ops::FRAGMENT_ROWS, int(HEAD_DIM + 8)));
+ fragment_mma(scores, queries[depth], keys);
+ }
+ scores.store(lane, score_slot, int(BK));
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ METAL_PRAGMA_UNROLL
+ for (ushort other = 1; other < SLICES; ++other) {
+ Scores partial;
+ partial.load_from(
+ lane,
+ fragment_source(exchange + (band * SLICES + (slice + other) % SLICES) * Layout::SCORE_TILE_ELEMENTS, int(BK))
+ );
+ scores.for_each_lane([&](ushort, ushort, thread float& score, thread float& value) { score += value; }, partial);
+ }
+ stage_int8_tile<HEAD_DIM, BK, true, NUM_SIMDGROUPS>(
+ value_codes,
+ value_scales,
+ kv_tile,
+ shape,
+ key_base,
+ params.k_len,
+ kv_head_index,
+ simdgroup * METAL_SIMD_SIZE + lane
+ );
+ if (is_kv_cache_ring || is_sliding_window || key_base + BK > params.q_off) {
+ scores.map_coords(lane, [&](short, short col, float score) {
+ const uint key = key_base + uint(col);
+ bool visible = key < params.k_len;
+ if (visible) {
+ if (!is_kv_cache_ring && !is_sliding_window && is_causal && trie_nodes <= 64) {
+ if (key >= params.q_off) {
+ visible =
+ is_trie ? ((trie_mask >> (key - params.q_off)) & 1ul) != 0ul : key <= params.q_off + query_position;
+ }
+ } else {
+ visible = should_use_key(
+ ring_params,
+ trie,
+ sliding_window_size,
+ query_position,
+ params.q_off,
+ suffix_position,
+ logical_query,
+ key,
+ is_kv_cache_ring,
+ is_causal,
+ is_trie,
+ is_sliding_window
+ );
+ }
+ }
+ return visible ? score : -INFINITY;
+ });
+ }
+ float block_max;
+ scores.row_reduce(&block_max, -INFINITY, [](float a, float b) { return metal::max(a, b); });
+ const float next_max = metal::max(running_max, block_max);
+ const float rescale = isfinite(running_max) ? fast::exp2(running_max - next_max) : 0.0f;
+ scores.map([&](float score) { return isfinite(next_max) ? fast::exp2(score - next_max) : 0.0f; });
+ float block_sum;
+ scores.row_reduce(&block_sum, 0.0f, [](float a, float b) { return a + b; });
+ denominator = denominator * rescale + block_sum;
+ running_max = next_max;
+ output.map([&](float value) { return value * rescale; });
+
+ METAL_PRAGMA_UNROLL
+ for (ushort key_fragment = 0; key_fragment < KEY_FRAGMENTS; ++key_fragment) {
+ METAL_PRAGMA_UNROLL
+ for (ushort col = 0; col < VALUE_FRAGMENTS; ++col) {
+ Value value;
+ value.load_from(
+ lane,
+ fragment_source(
+ kv_tile + key_fragment * Ops::FRAGMENT_ROWS * (HEAD_DIM + 8) + channel_base + col * Ops::FRAGMENT_COLS,
+ int(HEAD_DIM + 8)
+ )
+ );
+ SimdgroupMMA<float, 8, 8, float, half>::mma(
+ output.fragment_at(0, col),
+ scores.fragment_at(0, key_fragment),
+ value.fragment_at(0, 0),
+ output.fragment_at(0, col)
+ );
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ const float inverse_sum = denominator > 0.0f ? 1.0f / denominator : 0.0f;
+ output.map([&](float value) { return value * inverse_sum; });
+ const uint partial_row = (split * num_kv_heads + kv_head_index) * query_tiles * BLOCK_ROWS + row_base;
+ output.store(lane, partial_values + size_t(partial_row) * HEAD_DIM + channel_base, int(HEAD_DIM));
+ if (slice == 0 && position.x == 0) {
+ partial_maxima[partial_row + position.y] = running_max;
+ partial_denominators[partial_row + position.y] = denominator;
+ }
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs
index bce8d8e70..0d97a3bf7 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs
@@ -1,98 +1,146 @@
-use crate::backends::common::Backend;
+mod policy;
-mod error;
-mod gemm;
-mod gemm_grouped;
-mod int8;
-mod single_pass;
-mod two_pass;
-
-pub use error::AttentionMetalError;
-
-use crate::backends::{
- common::{
- BufferRef, CommandBufferEncoding,
- kernel::{
- AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, FullPrecisionInput,
- SigmoidGateKernel,
+use crate::{
+ backends::{
+ common::{
+ Backend, BufferMut, BufferRef, CommandBufferEncoding,
+ kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, kv_layout::KVLayout},
+ },
+ metal::{
+ Metal,
+ command_buffer::MetalCommandBufferEncoding,
+ context::MetalContext,
+ error::MetalError,
+ gpu_types::{attention::AttnParams, kv_layout},
+ kernel::{AttentionMatrixCombineMetalKernel, AttentionMatrixMetalKernel, AttentionVectorMetalKernel},
},
},
- metal::{Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, kernel::SigmoidGateMetalKernel},
+ data_type::DataType,
};
-#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
-enum MaskKind {
- None,
- Causal,
- Trie,
+pub struct AttentionMetalKernel {
+ config: AttentionKernelConfig,
+ use_mxu: bool,
+ tiles: Vec<KernelTile>,
+ vector: Vec<[AttentionVectorMetalKernel; 2]>,
+ combine: AttentionMatrixCombineMetalKernel,
}
-impl MaskKind {
- fn for_attention(
- is_causal: bool,
- is_trie: bool,
- ) -> Option<Self> {
- match (is_causal, is_trie) {
- (true, true) => Some(Self::Trie),
- (true, false) => Some(Self::Causal),
- (false, false) => Some(Self::None),
- (false, true) => None,
- }
- }
-
- fn is_causal(self) -> bool {
- !matches!(self, Self::None)
- }
-
- fn is_trie(self) -> bool {
- matches!(self, Self::Trie)
- }
+struct KernelTile {
+ rows: u32,
+ simdgroups: u32,
+ prefix: Option<AttentionMatrixMetalKernel>,
+ masked: AttentionMatrixMetalKernel,
+ trie: AttentionMatrixMetalKernel,
}
-const SINGLE_PASS_KV_THRESHOLD: u32 = 1_024;
-
-pub struct AttentionMetalKernel {
- config: AttentionKernelConfig,
- gate: Option<(SigmoidGateMetalKernel, u32)>,
- grouped: Option<gemm_grouped::AttentionGemmGrouped>,
- int8: Option<int8::Int8Attention>,
- gemm: Option<gemm::AttentionGemm>,
- two_pass: two_pass::AttentionTwoPass,
- single_pass: single_pass::AttentionSinglePass,
+impl AttentionMetalKernel {
+ fn new_with_mxu(
+ context: &MetalContext,
+ config: &AttentionKernelConfig,
+ use_mxu: bool,
+ ) -> Result<Self, MetalError> {
+ let slices = (config.head_dim
+ / if use_mxu {
+ kv_layout::SLICE_DIMS
+ } else {
+ 128
+ })
+ .max(1);
+ let mut tiles = Vec::new();
+ for simdgroups in [1, 2, 4, 6, 8] {
+ if simdgroups % slices != 0 {
+ continue;
+ }
+ let kernel = |mask_free, is_trie| {
+ AttentionMatrixMetalKernel::new(
+ context,
+ DataType::BF16,
+ config.head_dim,
+ use_mxu,
+ simdgroups,
+ config.is_causal,
+ config.is_kv_cache_ring,
+ config.sliding_window_size.is_some(),
+ mask_free,
+ is_trie,
+ config.num_groups,
+ )
+ };
+ tiles.push(KernelTile {
+ simdgroups,
+ rows: if use_mxu {
+ simdgroups * kv_layout::TILE_QUERIES / (config.head_dim / kv_layout::SLICE_DIMS)
+ } else {
+ simdgroups * 8 / slices
+ },
+ prefix: (use_mxu && !config.is_kv_cache_ring && config.sliding_window_size.is_none())
+ .then(|| kernel(true, false))
+ .transpose()?,
+ masked: kernel(false, false)?,
+ trie: kernel(false, true)?,
+ });
+ }
+ let mut vector = Vec::new();
+ if !use_mxu {
+ for (queries, split_kv) in [(1, false), (1, true), (2, true)] {
+ let kernel = |is_trie| {
+ AttentionVectorMetalKernel::new(
+ context,
+ if split_kv {
+ DataType::BF16
+ } else {
+ config.data_type
+ },
+ config.head_dim,
+ queries,
+ split_kv,
+ config.is_causal,
+ config.is_kv_cache_ring,
+ config.sliding_window_size.is_some(),
+ is_trie,
+ !split_kv && config.gate_row_stride.is_some(),
+ !split_kv && config.has_sinks,
+ config.num_groups,
+ )
+ };
+ vector.push([kernel(false)?, kernel(true)?]);
+ }
+ }
+ Ok(Self {
+ config: *config,
+ use_mxu,
+ tiles,
+ vector,
+ combine: AttentionMatrixCombineMetalKernel::new(
+ context,
+ config.data_type,
+ config.head_dim,
+ config.gate_row_stride.is_some(),
+ config.has_sinks,
+ )?,
+ })
+ }
}
impl AttentionKernel for AttentionMetalKernel {
type Backend = Metal;
- type Error = AttentionMetalError;
+ type Error = MetalError;
+
+ fn kv_layout(&self) -> KVLayout {
+ let layout = if self.use_mxu {
+ kv_layout::KVLayout::MxuTiled
+ } else {
+ kv_layout::KVLayout::RowMajor
+ };
+ KVLayout::new(self.config.head_dim, self.config.num_groups, kv_layout::TILE_KEYS, layout as u32)
+ }
fn new(
context: &MetalContext,
config: AttentionKernelConfig,
- ) -> Result<Self, AttentionMetalError> {
- let grouped = gemm_grouped::AttentionGemmGrouped::is_supported(&config)
- .then(|| gemm_grouped::AttentionGemmGrouped::new(&config));
- let int8 = int8::Int8Attention::is_supported(&config, context)
- .then(|| int8::Int8Attention::new(context, &config))
- .transpose()
- .map_err(AttentionMetalError::Backend)?;
- let gemm = gemm::AttentionGemm::is_supported(&config).then(|| gemm::AttentionGemm::new(&config));
- let gate = config
- .gate_row_stride
- .map(|stride| SigmoidGateMetalKernel::new(context, config.data_type).map(|kernel| (kernel, stride)))
- .transpose()?;
- Ok(Self {
- config,
- gate,
- grouped,
- int8,
- gemm,
- two_pass: two_pass::AttentionTwoPass::new(&config),
- single_pass: single_pass::AttentionSinglePass::new(&config),
- })
- }
-
- fn supports_int8(&self) -> bool {
- self.int8.is_some()
+ ) -> Result<Self, MetalError> {
+ Self::new_with_mxu(context, &config, context.supports_mxu && config.data_type == DataType::BF16)
}
fn encode(
@@ -104,76 +152,169 @@ impl AttentionKernel for AttentionMetalKernel {
>,
arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<<Metal as Backend>::ScratchBuffer, AttentionMetalError> {
+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
let command_buffer = &mut *command_buffer.debug_group("attention core");
- let (gate, suffix_length) = (arguments.gate, arguments.suffix_length);
- match input {
- AttentionInput::Int8(input) => {
- if arguments.sinks.is_some() {
- return Err(AttentionMetalError::UnsupportedInt8KV);
- }
- self.int8
- .as_ref()
- .ok_or(AttentionMetalError::UnsupportedInt8KV)?
- .encode(input, arguments, command_buffer)
- .map_err(AttentionMetalError::Backend)
- },
- AttentionInput::FullPrecision(input) => {
- self.encode_impl(input, arguments, command_buffer).map(|(mut output, gate_applied)| {
- if let (Some(gate), Some((kernel, stride)), false) = (gate, &self.gate, gate_applied) {
- kernel.encode(
- gate,
- &mut output,
- self.config.num_q_heads * self.config.head_dim,
- suffix_length,
- *stride,
- command_buffer,
- );
- }
- output
- })
- },
- }
- }
-}
-
-impl AttentionMetalKernel {
- fn encode_impl(
- &self,
- input: FullPrecisionInput<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<(<Metal as Backend>::ScratchBuffer, bool), AttentionMetalError> {
- let suffix_length = arguments.suffix_length;
- let gate_applied_by_two_pass = arguments.gate.is_some();
- let kv_length = arguments.cache.prefix_len() + suffix_length;
- let is_trie = arguments.trie.is_some();
- let is_ring = arguments.cache.ring_params().is_some();
- let mask = MaskKind::for_attention(self.config.is_causal, is_trie);
-
- if !is_ring
- && let Some(mask) = mask
- && let Some(grouped) = &self.grouped
- && grouped.should_encode(mask, suffix_length, kv_length, command_buffer.context().supports_mxu)
- {
- return grouped.encode(mask, input, arguments, command_buffer).map_err(AttentionMetalError::Backend);
- }
+ let AttentionArguments {
+ suffix_length,
+ trie,
+ cache,
+ gate,
+ sinks,
+ } = arguments;
+ let config = &self.config;
+ let (head_dim, num_q_heads, num_groups) = (config.head_dim, config.num_q_heads, config.num_groups);
+ let prefix_len = cache.prefix_len();
+ let kv_length = prefix_len + suffix_length;
- if suffix_length > 8
- && let Some(gemm) = &self.gemm
- {
- return Ok((gemm.encode(input, arguments, command_buffer)?, false));
- }
+ let gqa_factor = num_q_heads / num_groups;
+ let grouped_rows = gqa_factor * suffix_length;
+ let params = AttnParams {
+ q_strides: [0, grouped_rows * head_dim, head_dim],
+ k_strides: [0, head_dim, num_groups * head_dim],
+ v_strides: [0, head_dim, num_groups * head_dim],
+ o_strides: [0, head_dim, num_q_heads * head_dim],
+ gqa_factor,
+ scale: config.scale.unwrap_or(1.0 / (head_dim as f32).sqrt()),
+ q_len: suffix_length,
+ k_len: kv_length,
+ q_off: prefix_len,
+ nk: kv_length.div_ceil(kv_layout::TILE_KEYS),
+ };
+ let direct = !self.use_mxu && kv_length <= kv_layout::TILE_KEYS;
+ let vector_queries = if grouped_rows.is_multiple_of(2) {
+ 2
+ } else {
+ 1
+ };
+ let tile = (self.use_mxu || (!direct && grouped_rows > 4)).then(|| {
+ self.tiles
+ .iter()
+ .min_by_key(|tile| (grouped_rows.div_ceil(tile.rows) * tile.rows, std::cmp::Reverse(tile.rows)))
+ .unwrap()
+ });
+ let padded_rows = tile.map_or(grouped_rows, |tile| grouped_rows.next_multiple_of(tile.rows));
+ let split_rows = num_groups * padded_rows;
+ let num_splits = if direct {
+ 1
+ } else {
+ let (threadgroups, groups_per_core) = match tile {
+ None => (split_rows.div_ceil(4 * vector_queries), 4),
+ Some(tile) => (num_groups * (padded_rows / tile.rows), 8_u32.div_ceil(tile.simdgroups).max(2)),
+ };
+ let occupancy = (!self.use_mxu).then(|| {
+ (command_buffer.context().gpu_core_count.max(1) * groups_per_core).div_ceil(threadgroups.max(1))
+ });
+ policy::splits(&params, head_dim, split_rows, occupancy)
+ };
- if kv_length > SINGLE_PASS_KV_THRESHOLD {
- Ok((self.two_pass.encode(input, arguments, command_buffer)?, gate_applied_by_two_pass))
+ let rows = split_rows * num_splits;
+ let data_type = if direct {
+ config.data_type
+ } else {
+ DataType::BF16
+ };
+ let mut values = command_buffer.allocate_scratch_for_shape(&[rows, head_dim], data_type)?;
+ let mut statistics = if direct {
+ None
+ } else {
+ Some((
+ command_buffer.allocate_scratch_for_shape(&[rows], DataType::F32)?,
+ command_buffer.allocate_scratch_for_shape(&[rows], DataType::F32)?,
+ ))
+ };
+ let (maxima, sums) = statistics.as_mut().map_or((None, None), |(maxima, sums)| (Some(maxima), Some(sums)));
+ if let Some(tile) = tile {
+ let query_tiles = padded_rows / tile.rows;
+ let prefix_splits = tile.prefix.as_ref().map_or(0, |_| {
+ (0..num_splits)
+ .take_while(|split| ((split + 1) * params.nk / num_splits) * kv_layout::TILE_KEYS <= params.q_off)
+ .count() as u32
+ });
+ let maxima = maxima.unwrap();
+ let sums = sums.unwrap();
+ for (kernel, trie, split_base, split_count) in [
+ (tile.prefix.as_ref().unwrap_or(&tile.masked), None, 0, prefix_splits),
+ (trie.map_or(&tile.masked, |_| &tile.trie), trie, prefix_splits, num_splits - prefix_splits),
+ ] {
+ if split_count == 0 {
+ continue;
+ }
+ let range = |row_bytes: usize| {
+ let bytes = split_rows as usize * row_bytes;
+ split_base as usize * bytes..(split_base + split_count) as usize * bytes
+ };
+ kernel.encode(
+ input.query_codes,
+ input.query_scales,
+ input.k_codes,
+ input.k_scales,
+ input.v_codes,
+ input.v_scales,
+ trie,
+ cache.ring_params(),
+ config.sliding_window_size,
+ (&mut values).subrange_mut(range(head_dim as usize * DataType::BF16.size_in_bytes())),
+ (&mut *maxima).subrange_mut(range(DataType::F32.size_in_bytes())),
+ (&mut *sums).subrange_mut(range(DataType::F32.size_in_bytes())),
+ params,
+ query_tiles,
+ num_splits,
+ split_base,
+ split_count,
+ suffix_length,
+ command_buffer,
+ );
+ }
} else {
- Ok((self.single_pass.encode(input, arguments, command_buffer)?, false))
+ let variant = if direct {
+ 0
+ } else {
+ vector_queries as usize
+ };
+ self.vector[variant][usize::from(trie.is_some())].encode(
+ input.query_codes,
+ input.query_scales,
+ input.k_codes,
+ input.k_scales,
+ input.v_codes,
+ input.v_scales,
+ &mut values,
+ maxima,
+ sums,
+ trie,
+ cache.ring_params(),
+ config.sliding_window_size,
+ gate.filter(|_| direct),
+ sinks.filter(|_| direct),
+ config.gate_row_stride.filter(|_| direct),
+ params,
+ split_rows,
+ num_splits,
+ command_buffer,
+ );
}
+
+ let Some((maxima, sums)) = statistics else {
+ return Ok(values);
+ };
+ let mut output =
+ command_buffer.allocate_scratch_for_shape(&[suffix_length, num_q_heads, head_dim], config.data_type)?;
+ self.combine.encode(
+ &values,
+ &maxima,
+ &sums,
+ &mut output,
+ gate,
+ sinks,
+ params,
+ grouped_rows,
+ padded_rows,
+ num_groups,
+ num_splits,
+ config.gate_row_stride,
+ command_buffer,
+ );
+ Ok(output)
}
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/policy.rs
new file mode 100644
index 000000000..e6faac9d4
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/policy.rs
@@ -0,0 +1,40 @@
+use crate::{
+ backends::metal::gpu_types::{attention::AttnParams, kv_layout},
+ data_type::DataType,
+};
+
+const MXU_DECODE_MAX_SUFFIX: u32 = 64;
+const SHORT_SUFFIX_MAX: u32 = 4;
+const PREFILL_SPLIT_KEYS: u32 = 2048;
+const PREFILL_SPLIT_MIN_KV: u32 = 16384;
+const PREFILL_SPLIT_SCRATCH_BYTES: u64 = 256 << 20;
+
+pub fn splits(
+ params: &AttnParams,
+ head_dim: u32,
+ split_rows: u32,
+ occupancy: Option<u32>,
+) -> u32 {
+ const SHORT_SUFFIX_MAX_SPLITS: u32 = 16;
+ let splits = if params.q_len <= MXU_DECODE_MAX_SUFFIX {
+ occupancy.unwrap_or_else(|| {
+ let query_tokens = params.q_len.max(kv_layout::TILE_QUERIES);
+ let splits = (params.k_len as f32 / query_tokens as f32).sqrt().round() as u32;
+ if params.q_len <= SHORT_SUFFIX_MAX {
+ splits.min(SHORT_SUFFIX_MAX_SPLITS)
+ } else {
+ splits
+ }
+ })
+ } else if params.k_len >= PREFILL_SPLIT_MIN_KV {
+ let row_bytes =
+ head_dim as u64 * DataType::BF16.size_in_bytes() as u64 + 2 * DataType::F32.size_in_bytes() as u64;
+ let bytes_per_split = split_rows as u64 * row_bytes;
+ let scratch_splits = (PREFILL_SPLIT_SCRATCH_BYTES / bytes_per_split) as u32;
+ let rounded_splits = (params.k_len + PREFILL_SPLIT_KEYS / 2) / PREFILL_SPLIT_KEYS;
+ rounded_splits.min(scratch_splits)
+ } else {
+ 1
+ };
+ splits.clamp(1, params.nk.max(1))
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/prepare.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/prepare.metal
new file mode 100644
index 000000000..503d36ce3
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/prepare.metal
@@ -0,0 +1,165 @@
+#include <metal_stdlib>
+#include "../common/defines.h"
+#include "../common/dsl.h"
+#include "../hadamard_transform/hadamard_transform.h"
+#include "kv_layout.h"
+#include "int8_quantization.h"
+#include "../generated/qkv_norm.h"
+
+namespace kv_layout = uzu::kv_layout;
+
+template <typename T>
+METAL_FUNC T prepare_norm(
+ T value,
+ uint channel,
+ float inverse_rms,
+ const device float* scales,
+ bool has_scales,
+ bool enabled,
+ bool full_layer,
+ float scale_offset
+) {
+ if (!enabled)
+ return value;
+ const float normalized = float(value) * inverse_rms;
+ if (!has_scales)
+ return T(normalized);
+ const float scale = scales[channel] + scale_offset;
+ if (full_layer)
+ return T(normalized * scale);
+ return T(T(normalized) * T(scale));
+}
+
+template <typename ElementT, typename RopeT, uint HEAD_DIM>
+VARIANTS(ElementT, bfloat, float)
+VARIANTS(RopeT, float)
+VARIANTS(HEAD_DIM, 64, 128, 256, 512)
+PUBLIC KERNEL(AttentionPrepare)(
+ const device ElementT* qkvg, // [token, input_row_stride], with an optional trailing gate
+ device int8_t* q_codes,
+ device bfloat* q_scales,
+ device int8_t* k_codes OPTIONAL(append_kv),
+ device bfloat* k_scales OPTIONAL(append_kv),
+ device uchar* v_codes OPTIONAL(append_kv),
+ device bfloat* v_scales OPTIONAL(append_kv),
+ const device RopeT* cosines OPTIONAL(has_rope),
+ const device RopeT* sines OPTIONAL(has_rope),
+ const device float* query_norm_scales OPTIONAL(has_query_norm_scales),
+ const device float* key_norm_scales OPTIONAL(has_key_norm_scales),
+ const device float* value_norm_scales OPTIONAL(has_value_norm_scales),
+ const constant uzu::qkv_norm::QKVNormParams& norm_params,
+ const constant uint32_t& num_q_heads,
+ const constant uint32_t& rope_dim OPTIONAL(has_rope),
+ const constant uint32_t& kv_token_offset,
+ const constant uint32_t& input_row_stride,
+ const constant uint32_t& suffix_length,
+ const constant uint32_t& query_rows,
+ const bool has_rope SPECIALIZE,
+ const uint32_t num_kv_heads SPECIALIZE,
+ const uint32_t backend_opaque_layout SPECIALIZE,
+ const bool append_kv SPECIALIZE,
+ const bool has_query_norm_scales SPECIALIZE,
+ const bool has_key_norm_scales SPECIALIZE,
+ const bool has_value_norm_scales SPECIALIZE,
+ const uint32_t token_idx GROUPS(suffix_length),
+ const uint32_t head_idx GROUPS(num_q_heads + num_kv_heads * 2),
+ const uint32_t lane THREADS(METAL_SIMD_SIZE)
+) {
+ constexpr ushort VALUES_PER_LANE = HEAD_DIM / METAL_SIMD_SIZE;
+ const kv_layout::KVShape shape{HEAD_DIM, num_kv_heads, static_cast<kv_layout::KVLayout>(backend_opaque_layout)};
+ const ushort lane_index = ushort(lane);
+ const bool is_query = head_idx < num_q_heads;
+ if (!append_kv && !is_query) {
+ return;
+ }
+ const uint32_t gqa_factor = num_q_heads / num_kv_heads;
+ const size_t query_row =
+ is_query ? size_t(head_idx / gqa_factor) * query_rows + size_t(head_idx % gqa_factor) * suffix_length + token_idx
+ : 0;
+ const bool is_key = !is_query && head_idx < num_q_heads + num_kv_heads;
+ const uint32_t kv_head = is_key ? head_idx - num_q_heads : head_idx - num_q_heads - num_kv_heads;
+
+ const device ElementT* head = qkvg + size_t(token_idx) * input_row_stride + size_t(head_idx) * HEAD_DIM;
+ const uint norm_index = is_query ? 0 : is_key ? 1 : 2;
+ const bool norm_enabled = norm_params.enabled[norm_index];
+ const bool norm_full_layer = norm_params.full_layer[norm_index];
+ const float norm_scale_offset = norm_params.scale_offset[norm_index];
+ const bool has_scales = is_query ? has_query_norm_scales : is_key ? has_key_norm_scales : has_value_norm_scales;
+ const device float* norm_scales = nullptr;
+ if (has_scales)
+ norm_scales = is_query ? query_norm_scales : is_key ? key_norm_scales : value_norm_scales;
+ float inverse_rms = 1.0f;
+ if (norm_enabled) {
+ float sum = 0.0f;
+ METAL_PRAGMA_UNROLL
+ for (uint base = lane * 4; base < HEAD_DIM; base += METAL_SIMD_SIZE * 4) {
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < 4; ++i) {
+ const float value = float(head[base + i]);
+ sum += value * value;
+ }
+ }
+ inverse_rms = rsqrt(simd_sum(sum) / float(HEAD_DIM) + norm_params.epsilon[norm_index]);
+ }
+ float values[VALUES_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ const uint32_t channel = value_index * METAL_SIMD_SIZE + lane_index;
+ ElementT element = prepare_norm(
+ head[channel],
+ channel,
+ inverse_rms,
+ norm_scales,
+ has_scales,
+ norm_enabled,
+ norm_full_layer,
+ norm_scale_offset
+ );
+ if (has_rope && (is_query || is_key) && channel < rope_dim) {
+ const uint half_dim = rope_dim / 2;
+ const uint paired_channel = channel < half_dim ? channel + half_dim : channel - half_dim;
+ const float paired = float(prepare_norm(
+ head[paired_channel],
+ paired_channel,
+ inverse_rms,
+ norm_scales,
+ has_scales,
+ norm_enabled,
+ norm_full_layer,
+ norm_scale_offset
+ ));
+ const float signed_paired = channel < half_dim ? -paired : paired;
+ element = ElementT(
+ float(element) * float(cosines[token_idx * rope_dim + channel]) +
+ signed_paired * float(sines[token_idx * rope_dim + channel])
+ );
+ }
+ values[value_index] = float(element);
+ }
+
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ values[value_index] *= kv_layout::rotation_sign(value_index * METAL_SIMD_SIZE + lane_index);
+ }
+ simdgroup_hadamard_transform<VALUES_PER_LANE, METAL_SIMD_SIZE>(lane_index, values);
+
+ int codes[VALUES_PER_LANE];
+ const bfloat scale = kv_quantize_row<VALUES_PER_LANE>(values, codes);
+
+ const uint32_t key = kv_token_offset + token_idx;
+ const size_t scale_index = is_query ? query_row : shape.scale_index(key, kv_head);
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ const uint32_t channel = value_index * METAL_SIMD_SIZE + lane_index;
+ if (is_query) {
+ q_codes[scale_index * HEAD_DIM + channel] = int8_t(codes[value_index]);
+ } else if (is_key) {
+ k_codes[shape.k_code_index(key, kv_head, channel)] = int8_t(codes[value_index]);
+ } else {
+ v_codes[shape.v_code_index(key, kv_head, channel)] = uchar(codes[value_index] + kv_layout::V_CODE_BIAS);
+ }
+ }
+ if (lane_index == 0) {
+ (is_query ? q_scales : is_key ? k_scales : v_scales)[scale_index] = scale;
+ }
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/prepare_int8.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/prepare_int8.metal
deleted file mode 100644
index f26252997..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/prepare_int8.metal
+++ /dev/null
@@ -1,118 +0,0 @@
-#include <metal_stdlib>
-#include "../common/defines.h"
-#include "../common/dsl.h"
-#include "../hadamard_transform/hadamard_transform.h"
-#include "kv_layout.h"
-#include "rope.h"
-
-namespace kv_layout = uzu::kv_layout;
-
-UZU_CONST float INT8_MAX = 127.0f;
-
-template <typename ElementT, ushort VALUES_PER_LANE>
-METAL_FUNC ElementT kv_quantize_row(const thread float* values, thread int* codes) {
- float abs_max = 0.0f;
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- abs_max = metal::max(abs_max, metal::abs(values[value_index]));
- }
- abs_max = metal::simd_max(abs_max);
- const ElementT scale = ElementT(abs_max > 0.0f ? metal::precise::divide(abs_max, INT8_MAX) : 1.0f);
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- codes[value_index] =
- int(metal::clamp(metal::rint(metal::precise::divide(values[value_index], float(scale))), -INT8_MAX, INT8_MAX));
- }
- return scale;
-}
-
-template <typename ElementT, typename RopeT, uint HEAD_DIM>
-VARIANTS(ElementT, bfloat)
-VARIANTS(RopeT, float)
-VARIANTS(HEAD_DIM, 128, 256)
-PUBLIC KERNEL(AttentionPrepareInt8)(
- const device ElementT* qkvg,
- device ElementT* queries OPTIONAL(!quantize_queries),
- device int8_t* q_codes OPTIONAL(quantize_queries),
- device ElementT* q_scales OPTIONAL(quantize_queries),
- device int8_t* k_codes OPTIONAL(append_kv),
- device ElementT* k_scales OPTIONAL(append_kv),
- device uchar* v_codes OPTIONAL(append_kv),
- device ElementT* v_scales OPTIONAL(append_kv),
- const device RopeT* cosines OPTIONAL(has_rope),
- const device RopeT* sines OPTIONAL(has_rope),
- const constant uint32_t& num_q_heads,
- const constant uint32_t& rope_dim OPTIONAL(has_rope),
- const constant uint32_t& kv_token_offset,
- const constant uint32_t& input_row_stride,
- const constant uint32_t& suffix_length,
- const constant uint32_t& query_rows,
- const bool has_rope SPECIALIZE,
- const bool quantize_queries SPECIALIZE,
- const uint32_t num_kv_heads SPECIALIZE,
- const bool append_kv SPECIALIZE,
- const uint32_t token_idx GROUPS(suffix_length),
- const uint32_t head_idx GROUPS(num_q_heads + num_kv_heads * 2),
- const uint32_t lane THREADS(METAL_SIMD_SIZE)
-) {
- constexpr ushort VALUES_PER_LANE = HEAD_DIM / METAL_SIMD_SIZE;
- const kv_layout::Int8KVShape shape{HEAD_DIM, num_kv_heads};
- const ushort lane_index = ushort(lane);
- const bool is_query = head_idx < num_q_heads;
- if (!append_kv && !is_query) {
- return;
- }
- const uint32_t gqa_factor = num_q_heads / num_kv_heads;
- const size_t query_row =
- is_query ? size_t(head_idx / gqa_factor) * query_rows + size_t(head_idx % gqa_factor) * suffix_length + token_idx
- : 0;
- const bool is_key = !is_query && head_idx < num_q_heads + num_kv_heads;
- const uint32_t kv_head = is_key ? head_idx - num_q_heads : head_idx - num_q_heads - num_kv_heads;
-
- const device ElementT* head = qkvg + size_t(token_idx) * input_row_stride + size_t(head_idx) * HEAD_DIM;
- float values[VALUES_PER_LANE];
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- const uint32_t channel = value_index * METAL_SIMD_SIZE + lane_index;
- ElementT element = head[channel];
- if (has_rope && (is_query || is_key) && channel < rope_dim) {
- element = apply_rope(head, cosines, sines, token_idx, channel, rope_dim);
- }
- values[value_index] = float(element);
- }
-
- if (is_query && !quantize_queries) {
- const size_t row = size_t(head_idx) * suffix_length + token_idx;
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- queries[row * HEAD_DIM + value_index * METAL_SIMD_SIZE + lane_index] = ElementT(values[value_index]);
- }
- return;
- }
-
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- values[value_index] *= kv_layout::rotation_sign(value_index * METAL_SIMD_SIZE + lane_index);
- }
- simdgroup_hadamard_transform<VALUES_PER_LANE, METAL_SIMD_SIZE>(lane_index, values);
-
- int codes[VALUES_PER_LANE];
- const ElementT scale = kv_quantize_row<ElementT, VALUES_PER_LANE>(values, codes);
-
- const uint32_t key = kv_token_offset + token_idx;
- const size_t scale_index = is_query ? query_row : shape.scale_index(key, kv_head);
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- const uint32_t channel = value_index * METAL_SIMD_SIZE + lane_index;
- if (is_query) {
- q_codes[scale_index * HEAD_DIM + channel] = int8_t(codes[value_index]);
- } else if (is_key) {
- k_codes[shape.k_code_index(key, kv_head, channel)] = int8_t(codes[value_index]);
- } else {
- v_codes[shape.v_code_index(key, kv_head, channel)] = uchar(codes[value_index] + kv_layout::V_CODE_BIAS);
- }
- }
- if (lane_index == 0) {
- (is_query ? q_scales : is_key ? k_scales : v_scales)[scale_index] = scale;
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal
deleted file mode 100644
index 1ddac82c7..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal
+++ /dev/null
@@ -1,101 +0,0 @@
-#include <metal_stdlib>
-#include "../common/defines.h"
-#include "../common/dsl.h"
-
-using namespace metal;
-#define GRAIN_SIZE 4
-
-// QKV norm: normalize per-head vectors (small head_dim) efficiently.
-//
-// Strategy:
-// - One SIMD-group (32 threads) processes one head.
-// - One threadgroup (one SIMD-group) is dispatched per head.
-template <typename InputT, typename ScaleT, typename OutputT, typename AccumT>
-VARIANTS(InputT, float, bfloat)
-VARIANTS(ScaleT, float, bfloat)
-VARIANTS(OutputT, float, bfloat)
-VARIANTS(AccumT, float)
-PUBLIC KERNEL(QKVNorm)(
- const device InputT* qkvg_input OPTIONAL(!in_place),
- const device ScaleT* scales OPTIONAL(has_scales),
- device OutputT* qkvg_output,
- constant uint& batch_size,
- constant uint& input_row_stride,
- constant uint& head_dim,
- constant float& epsilon,
- constant float& scale_offset,
- constant uint& head_offset,
- constant uint& head_count,
- constant bool& full_layer,
- const uint batch_idx GROUPS(batch_size),
- const uint head_idx GROUPS(head_count),
- const uint lane_id THREADS(METAL_SIMD_SIZE),
- const bool in_place SPECIALIZE,
- const bool has_scales SPECIALIZE
-) {
- if (in_place) {
- qkvg_input = (const device InputT*)qkvg_output;
- }
-
- if (head_count == 0u || head_dim == 0u)
- return;
-
- const ulong slice_offset =
- (ulong)batch_idx * (ulong)input_row_stride + (ulong)(head_offset + head_idx) * (ulong)head_dim;
-
- const device InputT* input_data = qkvg_input + slice_offset;
- const device ScaleT* scales_data = scales;
- device OutputT* output_data = qkvg_output + slice_offset;
- const uint element_count = head_dim;
-
- AccumT partial_sum = static_cast<AccumT>(0.0f);
-
- // Sum of squares: each lane processes GRAIN_SIZE elements per iteration.
- for (uint base_i = lane_id * GRAIN_SIZE; base_i < element_count; base_i += METAL_SIMD_SIZE * GRAIN_SIZE) {
- AccumT vals[GRAIN_SIZE];
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- vals[j] = (i < element_count) ? static_cast<AccumT>(input_data[i]) : 0.0f;
- }
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- partial_sum += vals[j] * vals[j];
- }
- }
-
- // SIMD-group reduction.
- AccumT total_sum = simd_sum(partial_sum);
-
- // RMS factor.
- AccumT mean_square = static_cast<AccumT>(total_sum) / static_cast<AccumT>(element_count);
- AccumT rms_norm = rsqrt(mean_square + static_cast<AccumT>(epsilon));
-
- // Normalize + scale.
- for (uint base_i = lane_id * GRAIN_SIZE; base_i < element_count; base_i += METAL_SIMD_SIZE * GRAIN_SIZE) {
- AccumT vals[GRAIN_SIZE];
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- vals[j] = (i < element_count) ? static_cast<AccumT>(input_data[i]) : 0.0f;
- }
-
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- if (i >= element_count)
- continue;
-
- AccumT normalized_high = vals[j] * rms_norm;
-
- if (!has_scales) {
- output_data[i] = static_cast<OutputT>(normalized_high);
- } else if (full_layer) {
- AccumT scale_value_high = static_cast<AccumT>(scales_data[i]) + static_cast<AccumT>(scale_offset);
- output_data[i] = static_cast<OutputT>(normalized_high * scale_value_high);
- } else {
- OutputT normalized_low = static_cast<OutputT>(normalized_high);
- OutputT scale_value_low =
- static_cast<OutputT>(static_cast<AccumT>(scales_data[i]) + static_cast<AccumT>(scale_offset));
- OutputT product_low = normalized_low * scale_value_low;
- output_data[i] = static_cast<OutputT>(product_low);
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal
deleted file mode 100644
index 228b30f40..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal
+++ /dev/null
@@ -1,18 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/sigmoid_gate.h"
-
-template <typename T>
-VARIANTS(T, bfloat)
-PUBLIC KERNEL(SigmoidGate)(
- const device T* gate,
- device T* output,
- const constant uint& gate_dim,
- const constant uint& batch_dim,
- const constant uint& gate_row_stride,
- const uint gate_idx AXIS(gate_dim, 256),
- const uint batch_idx AXIS(batch_dim, 1)
-) {
- const uint output_idx = batch_idx * gate_dim + gate_idx;
- output[output_idx] = uzu::apply_sigmoid_gate(output[output_idx], gate[batch_idx * gate_row_stride + gate_idx]);
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs
deleted file mode 100644
index bdfd9c1f8..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs
+++ /dev/null
@@ -1,90 +0,0 @@
-use std::collections::{HashMap, hash_map::Entry};
-
-use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
-
-use super::FullPrecisionInput;
-use crate::backends::{
- common::{
- Backend, BufferRef, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernelConfig, AttentionSinglePassKernel},
- },
- metal::{
- Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError,
- kernel::AttentionSinglePassMetalKernel,
- },
-};
-
-pub struct AttentionSinglePass {
- kernels: Mutex<HashMap<bool, AttentionSinglePassMetalKernel>>,
- config: AttentionKernelConfig,
-}
-
-impl AttentionSinglePass {
- pub fn new(config: &AttentionKernelConfig) -> Self {
- Self {
- kernels: Mutex::new(HashMap::new()),
- config: *config,
- }
- }
-
- fn get_or_create(
- &self,
- context: &MetalContext,
- is_trie: bool,
- ) -> Result<MappedMutexGuard<'_, AttentionSinglePassMetalKernel>, MetalError> {
- let mut kernels = self.kernels.lock();
- if let Entry::Vacant(entry) = kernels.entry(is_trie) {
- let kernel = AttentionSinglePassMetalKernel::new(
- context,
- self.config.data_type,
- self.config.head_dim,
- self.config.has_sinks,
- self.config.is_kv_cache_ring,
- self.config.is_causal,
- is_trie,
- self.config.sliding_window_size.is_some(),
- )?;
- entry.insert(kernel);
- }
- Ok(MutexGuard::map(kernels, |kernels| kernels.get_mut(&is_trie).expect("kernel was just initialized")))
- }
-
- pub fn encode(
- &self,
- input: FullPrecisionInput<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
- let config = self.config;
- let mut output = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, config.head_dim],
- config.data_type,
- )?;
- let kernel = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;
- kernel.encode(
- input.queries,
- input.keys,
- input.values,
- &mut output,
- config.num_q_heads / config.num_groups,
- arguments.cache.prefix_len() + arguments.suffix_length,
- config.head_dim,
- config.num_groups * config.head_dim,
- config.head_dim,
- config.num_groups * config.head_dim,
- arguments.cache.ring_params(),
- config.scale.unwrap_or(1.0 / (config.head_dim as f32).sqrt()),
- arguments.trie,
- config.sliding_window_size,
- arguments.sinks,
- config.num_q_heads,
- arguments.suffix_length,
- command_buffer,
- );
- Ok(output)
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs
deleted file mode 100644
index 39d019c07..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-use std::collections::{HashMap, hash_map::Entry};
-
-use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
-
-use super::FullPrecisionInput;
-use crate::{
- backends::{
- common::{
- Backend, BufferRef, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernelConfig},
- },
- metal::{
- Metal,
- command_buffer::MetalCommandBufferEncoding,
- context::MetalContext,
- error::MetalError,
- kernel::{AttentionTwoPass1MetalKernel, AttentionTwoPass2MetalKernel},
- },
- },
- data_type::DataType,
-};
-
-const PARTIAL_DATA_TYPE: DataType = DataType::F32;
-const PARTIAL_BLOCKS: u32 = 32;
-
-pub struct AttentionTwoPass {
- passes: Mutex<HashMap<bool, AttentionTwoPass1MetalKernel>>,
- second: Mutex<Option<AttentionTwoPass2MetalKernel>>,
- config: AttentionKernelConfig,
-}
-
-impl AttentionTwoPass {
- pub fn new(config: &AttentionKernelConfig) -> Self {
- Self {
- passes: Mutex::new(HashMap::new()),
- second: Mutex::new(None),
- config: *config,
- }
- }
-
- fn get_or_create(
- &self,
- context: &MetalContext,
- is_trie: bool,
- ) -> Result<MappedMutexGuard<'_, AttentionTwoPass1MetalKernel>, MetalError> {
- let mut passes = self.passes.lock();
- if let Entry::Vacant(entry) = passes.entry(is_trie) {
- entry.insert(AttentionTwoPass1MetalKernel::new(
- context,
- self.config.data_type,
- self.config.head_dim,
- self.config.has_sinks,
- self.config.is_kv_cache_ring,
- self.config.is_causal,
- is_trie,
- self.config.sliding_window_size.is_some(),
- )?);
- }
- Ok(MutexGuard::map(passes, |passes| passes.get_mut(&is_trie).expect("passes were just initialized")))
- }
-
- fn get_or_create_second(
- &self,
- context: &MetalContext,
- ) -> Result<MappedMutexGuard<'_, AttentionTwoPass2MetalKernel>, MetalError> {
- let mut second = self.second.lock();
- if second.is_none() {
- *second = Some(AttentionTwoPass2MetalKernel::new(
- context,
- self.config.data_type,
- self.config.head_dim,
- self.config.gate_row_stride.is_some(),
- )?);
- }
- Ok(MutexGuard::map(second, |second| second.as_mut().expect("pass was just initialized")))
- }
-
- pub fn encode(
- &self,
- input: FullPrecisionInput<
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
- >,
- arguments: AttentionArguments<'_, Metal, impl BufferRef<Backend = Metal>, impl BufferRef<Backend = Metal>>,
- command_buffer: &mut MetalCommandBufferEncoding,
- ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
- let config = self.config;
- let mut partials = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS, config.head_dim],
- PARTIAL_DATA_TYPE,
- )?;
- let mut sums = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS],
- PARTIAL_DATA_TYPE,
- )?;
- let mut maxs = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS],
- PARTIAL_DATA_TYPE,
- )?;
- let first = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;
- first.encode(
- input.queries,
- input.keys,
- input.values,
- &mut partials,
- &mut sums,
- &mut maxs,
- config.num_q_heads / config.num_groups,
- arguments.cache.prefix_len() + arguments.suffix_length,
- config.head_dim,
- config.num_groups * config.head_dim,
- config.head_dim,
- config.num_groups * config.head_dim,
- arguments.cache.ring_params(),
- config.scale.unwrap_or(1.0 / (config.head_dim as f32).sqrt()),
- config.num_q_heads,
- arguments.suffix_length,
- arguments.trie,
- config.sliding_window_size,
- arguments.sinks,
- command_buffer,
- );
- let mut output = command_buffer.allocate_scratch_for_shape(
- &[arguments.suffix_length, config.num_q_heads, config.head_dim],
- config.data_type,
- )?;
- let second = self.get_or_create_second(command_buffer.context())?;
- second.encode(
- &partials,
- &sums,
- &maxs,
- &mut output,
- arguments.gate,
- config.num_q_heads,
- arguments.suffix_length,
- config.gate_row_stride,
- command_buffer,
- );
- Ok(output)
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/vector.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/vector.metal
new file mode 100644
index 000000000..c04c9233e
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/vector.metal
@@ -0,0 +1,208 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+#include "../common/thread_context.h"
+#include "../common/sigmoid_gate.h"
+#include "../hadamard_transform/hadamard_transform.h"
+#include "../generated/attention.h"
+#include "kv_layout.h"
+#include "mask.h"
+
+using namespace metal;
+
+template <typename T, uint HEAD_DIM, uint QUERIES, bool SPLIT_KV>
+VARIANTS(T, bfloat, float)
+VARIANTS(HEAD_DIM, 64, 128, 256, 512)
+VARIANTS(QUERIES, 1, 2)
+VARIANTS(SPLIT_KV, false, true)
+CONSTRAINT(SPLIT_KV || QUERIES == 1)
+CONSTRAINT(!SPLIT_KV || T == "bfloat")
+KERNEL(AttentionVector)(
+ const device int8_t* query_codes,
+ const device bfloat* query_scales,
+ const device int8_t* key_codes,
+ const device bfloat* key_scales,
+ const device uchar* value_codes,
+ const device bfloat* value_scales,
+ device T* output,
+ device float* partial_maxs OPTIONAL(SPLIT_KV),
+ device float* partial_sums OPTIONAL(SPLIT_KV),
+ const device uzu::trie::TrieNode* trie OPTIONAL(is_trie),
+ const constant uzu::ring::RingParams& ring_params OPTIONAL(is_kv_cache_ring),
+ const constant uint& sliding_window_size OPTIONAL(is_sliding_window),
+ const device T* gate OPTIONAL(!SPLIT_KV && has_gate),
+ const device T* sinks OPTIONAL(!SPLIT_KV && has_sinks),
+ const constant uint& gate_row_stride OPTIONAL(!SPLIT_KV && has_gate),
+ const constant uzu::attention::AttnParams& params,
+ const constant uint& rows,
+ const constant uint& num_splits,
+ const bool is_causal SPECIALIZE,
+ const bool is_kv_cache_ring SPECIALIZE,
+ const bool is_sliding_window SPECIALIZE,
+ const bool is_trie SPECIALIZE,
+ const bool has_gate SPECIALIZE,
+ const bool has_sinks SPECIALIZE,
+ const uint num_kv_heads SPECIALIZE,
+ const ThreadContext thread_context,
+ const uint group GROUPS(rows.div_ceil(4 * QUERIES)),
+ const uint split GROUPS(num_splits),
+ const uint thread_index THREADS(4 * METAL_SIMD_SIZE)
+) {
+ const uint row = (group * 4 + thread_context.simdgroup_index) * QUERIES;
+ if (row >= rows)
+ return;
+ constexpr uint N = (HEAD_DIM + 127) / 128;
+ const ushort lane = ushort(thread_context.simd_lane_id);
+ constexpr uint TILE_KEYS = SPLIT_KV ? 32 : 4;
+ constexpr uint CHANNEL_LANES = SPLIT_KV ? 4 : 8;
+ constexpr uint KEY_ROWS = METAL_SIMD_SIZE / CHANNEL_LANES;
+ constexpr uint KEYS_PER_LANE = SPLIT_KV ? 4 : 1;
+ const uint key_row = lane / CHANNEL_LANES;
+ const uint channel_group = lane % CHANNEL_LANES;
+ const uint kv_head = row / (params.q_len * params.gqa_factor);
+ const uint suffix_position = is_kv_cache_ring ? ring_params.ring_length : params.q_off;
+ const uzu::kv_layout::KVShape shape{HEAD_DIM, num_kv_heads, uzu::kv_layout::KVLayout::RowMajor};
+ uint q_position[QUERIES];
+ uint query_position[QUERIES];
+ float query_scale[QUERIES];
+ float4 result[QUERIES][N] = {};
+ float maximum[QUERIES];
+ float denominator[QUERIES];
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q) {
+ q_position[q] = (row + q) % params.q_len;
+ query_position[q] = suffix_position + (is_trie ? trie[q_position[q]].height : q_position[q]);
+ query_scale[q] = float(query_scales[row + q]) * params.scale * M_LOG2E_F;
+ maximum[q] = !SPLIT_KV && has_sinks ? float(sinks[(row + q) / params.q_len]) * M_LOG2E_F : -INFINITY;
+ denominator[q] = !SPLIT_KV && has_sinks ? 1.0f : 0.0f;
+ }
+ const uint begin = SPLIT_KV ? split * params.nk / num_splits : 0;
+ const uint end = SPLIT_KV ? (split + 1) * params.nk / num_splits : (params.k_len + TILE_KEYS - 1) / TILE_KEYS;
+ for (uint block = begin; block < end; ++block) {
+ const uint first_key = block * TILE_KEYS;
+ const size_t region = shape.block_region(first_key / 32, kv_head) + (first_key % 32) * HEAD_DIM;
+ float4 scores[QUERIES] = {};
+ _Pragma("clang loop unroll_count(4)") for (uint fragment_index = 0; fragment_index < HEAD_DIM / (CHANNEL_LANES * 4);
+ ++fragment_index) {
+ const uint channel = fragment_index * CHANNEL_LANES * 4 + channel_group * 4;
+ float4 keys[KEYS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < KEYS_PER_LANE; ++i) {
+ keys[i] = float4(
+ *reinterpret_cast<const device char4*>(key_codes + region + (key_row + i * KEY_ROWS) * HEAD_DIM + channel)
+ );
+ }
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q) {
+ const float4 query =
+ float4(*reinterpret_cast<const device char4*>(query_codes + size_t(row + q) * HEAD_DIM + channel));
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < KEYS_PER_LANE; ++i)
+ scores[q][i] += dot(query, keys[i]);
+ }
+ }
+ float4 probabilities[QUERIES];
+ float correction[QUERIES];
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q) {
+ METAL_PRAGMA_UNROLL
+ for (ushort offset = 1; offset < CHANNEL_LANES; offset *= 2)
+ scores[q] += simd_shuffle_xor(scores[q], offset);
+ float4 value_scale = {};
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < KEYS_PER_LANE; ++i) {
+ const uint key = first_key + key_row + i * KEY_ROWS;
+ const bool visible = key < params.k_len && should_use_key(
+ ring_params,
+ trie,
+ sliding_window_size,
+ q_position[q],
+ params.q_off,
+ suffix_position,
+ query_position[q],
+ key,
+ is_kv_cache_ring,
+ is_causal,
+ is_trie,
+ is_sliding_window
+ );
+ const size_t scale_index = shape.scale_index(key, kv_head);
+ scores[q][i] = visible ? scores[q][i] * query_scale[q] * float(key_scales[scale_index]) : -INFINITY;
+ value_scale[i] = visible ? float(value_scales[scale_index]) : 0.0f;
+ }
+ const float tile_max =
+ simd_max(SPLIT_KV ? max(max(scores[q].x, scores[q].y), max(scores[q].z, scores[q].w)) : scores[q].x);
+ const float next_max = max(maximum[q], tile_max);
+ correction[q] = denominator[q] > 0.0f ? fast::exp2(maximum[q] - next_max) : 0.0f;
+ probabilities[q] = next_max == -INFINITY ? float4(0) : fast::exp2(scores[q] - next_max);
+ denominator[q] = denominator[q] * correction[q] +
+ simd_sum(
+ SPLIT_KV ? probabilities[q].x + probabilities[q].y + probabilities[q].z + probabilities[q].w
+ : probabilities[q].x
+ ) / float(CHANNEL_LANES);
+ probabilities[q] *= value_scale;
+ maximum[q] = next_max;
+ }
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q) {
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < N; ++i)
+ result[q][i] *= correction[q];
+ }
+ for (uint key = 0; key < TILE_KEYS; ++key) {
+ float weights[QUERIES];
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q)
+ weights[q] = simd_shuffle(probabilities[q][key / KEY_ROWS], ushort((key % KEY_ROWS) * CHANNEL_LANES));
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < N; ++i) {
+ const uint channel = i * 128 + lane * 4;
+ if (channel < HEAD_DIM) {
+ const uint packed = *reinterpret_cast<const device uint*>(value_codes + region + key * HEAD_DIM + channel);
+ const float4 value = float4(as_type<char4>(packed ^ 0x80808080u));
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q)
+ result[q][i] += weights[q] * value;
+ }
+ }
+ }
+ }
+ METAL_PRAGMA_UNROLL
+ for (uint q = 0; q < QUERIES; ++q) {
+ const float inverse = denominator[q] > 0.0f ? 1.0f / denominator[q] : 0.0f;
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < N; ++i)
+ result[q][i] *= inverse;
+ if constexpr (SPLIT_KV) {
+ const size_t partial_row = size_t(split) * rows + row + q;
+ METAL_PRAGMA_UNROLL
+ for (uint i = 0; i < N; ++i) {
+ const uint channel = i * 128 + lane * 4;
+ if (channel < HEAD_DIM)
+ *reinterpret_cast<device bfloat4*>(output + partial_row * HEAD_DIM + channel) = bfloat4(result[q][i]);
+ }
+ if (lane == 0) {
+ partial_maxs[partial_row] = maximum[q];
+ partial_sums[partial_row] = denominator[q];
+ }
+ } else {
+ constexpr ushort VALUES_PER_LANE = HEAD_DIM / METAL_SIMD_SIZE;
+ float rotated[VALUES_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < VALUES_PER_LANE; ++i) {
+ const float4 values = simd_shuffle(result[q][i / 4], ushort((i % 4) * 8 + lane / 4));
+ rotated[i] = values[lane % 4];
+ }
+ simdgroup_hadamard_transform<VALUES_PER_LANE, METAL_SIMD_SIZE>(lane, rotated);
+ const uint q_head = (row + q) / params.q_len;
+ const uint output_base = q_head * params.o_strides[1] + q_position[q] * params.o_strides[2];
+ METAL_PRAGMA_UNROLL
+ for (ushort i = 0; i < VALUES_PER_LANE; ++i) {
+ const uint channel = i * METAL_SIMD_SIZE + lane;
+ T value = T(rotated[i] * uzu::kv_layout::rotation_sign(channel));
+ if (has_gate)
+ value = uzu::apply_sigmoid_gate(value, gate[q_position[q] * gate_row_stride + q_head * HEAD_DIM + channel]);
+ output[output_base + channel] = value;
+ }
+ }
+ }
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/attention.h b/crates/uzu-engine/src/backends/metal/kernel/generated/attention.h
index 55f58b29f..1b17c93f2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/generated/attention.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/attention.h
@@ -15,10 +15,6 @@ typedef struct {
uint32_t q_len;
uint32_t k_len;
uint32_t q_off;
- uint32_t nq_aligned;
- uint32_t q_rem;
uint32_t nk;
- uint32_t nk_aligned;
- uint32_t k_rem;
} AttnParams;
} // namespace uzu::attention
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/kv_layout.h b/crates/uzu-engine/src/backends/metal/kernel/generated/kv_layout.h
index 771093a27..b3550113c 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/generated/kv_layout.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/kv_layout.h
@@ -5,6 +5,18 @@
using namespace metal;
namespace uzu::kv_layout {
+static constant constexpr int16_t V_CODE_BIAS = 128;
+
+static constant constexpr uint32_t WORD_BITS = 32;
+
+static constant constexpr uint32_t ROTATION_SIGN_BITS[8] =
+ {2654435769, 2246822507, 3266489909, 668265263, 374761393, 3210233709, 2496678331, 3605593784};
+
+enum class KVLayout : uint32_t {
+ RowMajor = 0,
+ MxuTiled = 1,
+};
+
static constant constexpr uint32_t TILE_KEYS = 32;
static constant constexpr uint32_t TILE_QUERIES = 16;
@@ -15,16 +27,9 @@ static constant constexpr uint32_t FRAGMENT_BYTES = TILE_KEYS * TILE_DIMS;
static constant constexpr uint32_t SLICE_DIMS = 64;
-static constant constexpr int16_t V_CODE_BIAS = 128;
-
static constant constexpr uint32_t GROUP_ROWS = 8;
static constant constexpr uint32_t LANE_COLS = 4;
static constant constexpr uint32_t LANE_BYTES = TILE_KEYS / GROUP_ROWS * LANE_COLS;
-
-static constant constexpr uint32_t WORD_BITS = 32;
-
-static constant constexpr uint32_t ROTATION_SIGN_BITS[8] =
- {2654435769, 2246822507, 3266489909, 668265263, 374761393, 3210233709, 2496678331, 3605593784};
} // namespace uzu::kv_layout
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/qkv_norm.h b/crates/uzu-engine/src/backends/metal/kernel/generated/qkv_norm.h
new file mode 100644
index 000000000..30a598922
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/qkv_norm.h
@@ -0,0 +1,14 @@
+// Auto-generated from gpu_types/qkv_norm - do not edit manually
+#pragma once
+
+#include <metal_stdlib>
+using namespace metal;
+
+namespace uzu::qkv_norm {
+typedef struct {
+ uint32_t enabled[3];
+ uint32_t full_layer[3];
+ float epsilon[3];
+ float scale_offset[3];
+} QKVNormParams;
+} // namespace uzu::qkv_norm
diff --git a/crates/uzu-engine/src/backends/metal/kernel/hadamard_transform/hadamard_transform.h b/crates/uzu-engine/src/backends/metal/kernel/hadamard_transform/hadamard_transform.h
index 4d6afe56b..54bf166cf 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/hadamard_transform/hadamard_transform.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/hadamard_transform/hadamard_transform.h
@@ -23,7 +23,10 @@ static METAL_FUNC void simdgroup_hadamard_transform(ushort lane_index, thread fl
LANES <= METAL_SIMD_SIZE && (LANES & (LANES - 1)) == 0,
"lanes must be a power of two within a simdgroup"
);
- static_assert(SIZE == 32 || SIZE == 64 || SIZE == 128 || SIZE == 256, "transform size must be 32, 64, 128 or 256");
+ static_assert(
+ SIZE == 32 || SIZE == 64 || SIZE == 128 || SIZE == 256 || SIZE == 512,
+ "transform size must be 32, 64, 128, 256 or 512"
+ );
METAL_PRAGMA_UNROLL
for (ushort stride = 1; stride < VALUES_PER_LANE; stride <<= 1) {
METAL_PRAGMA_UNROLL
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang
index e6ffafab0..e06adca3e 100644
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang
@@ -3,8 +3,14 @@ import definitions;
[[Variants("HEAD_DIM", "128")]]
[[Public]] [[Kernel]] func AncestorAttention<let HEAD_DIM: uint32_t>(
- StructuredBuffer<BFloat16> prefix_kv,
- RWStructuredBuffer<BFloat16> node_kv,
+ StructuredBuffer<int8_t> prefix_k_codes,
+ StructuredBuffer<BFloat16> prefix_k_scales,
+ StructuredBuffer<uint8_t> prefix_v_codes,
+ StructuredBuffer<BFloat16> prefix_v_scales,
+ RWStructuredBuffer<int8_t> node_k_codes,
+ RWStructuredBuffer<BFloat16> node_k_scales,
+ RWStructuredBuffer<uint8_t> node_v_codes,
+ RWStructuredBuffer<BFloat16> node_v_scales,
StructuredBuffer<BFloat16> current_qkv,
StructuredBuffer<float> cosines,
StructuredBuffer<float> sines,
@@ -20,6 +26,7 @@ import definitions;
uint32_t max_depth,
float scale,
[[Specialize]] uint32_t num_heads,
+ [[Specialize]] uint32_t backend_opaque_layout,
ThreadContext thread_context,
[[Groups("(rows * num_heads).div_ceil(4)")]] uint32_t group,
[[Threads("(4 * 32)")]] uint32_t lid,
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang
deleted file mode 100644
index 8f72ac54a..000000000
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang
+++ /dev/null
@@ -1,27 +0,0 @@
-// Autogenerated stub
-import definitions;
-
-[[Variants("ElementT", "BFloat16")]]
-[[Variants("RopeT", "float")]]
-[[Public]] [[Kernel]] func AttentionPrepare<ElementT, RopeT>(
- StructuredBuffer<ElementT> qkvg,
- RWStructuredBuffer<ElementT> queries,
- [[Optional("has_kv")]] RWStructuredBuffer<ElementT> keys,
- [[Optional("has_kv")]] RWStructuredBuffer<ElementT> values,
- [[Optional("has_rope")]] StructuredBuffer<RopeT> cosines,
- [[Optional("has_rope")]] StructuredBuffer<RopeT> sines,
- uint32_t num_q_heads,
- [[Optional("has_kv")]] uint32_t num_kv_heads,
- uint32_t head_dim,
- [[Optional("has_rope")]] uint32_t rope_dim,
- [[Optional("has_kv")]] uint32_t kv_token_offset,
- uint32_t input_row_stride,
- uint32_t batch_dim,
- [[Specialize]] bool has_kv,
- [[Specialize]] bool has_rope,
- [[Axis("head_dim", "128")]] uint32_t head_dim_idx,
- [[Axis("num_q_heads + num_kv_heads.unwrap_or(0) * 2", "1")]] uint32_t head_idx,
- [[Axis("batch_dim", "1")]] uint32_t batch_idx,
-) {
- // TODO
-}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang
deleted file mode 100644
index c1a89f702..000000000
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang
+++ /dev/null
@@ -1,37 +0,0 @@
-// Autogenerated stub
-import definitions;
-import generated.ring;
-import generated.trie;
-
-[[Variants("T", "BFloat16")]]
-[[Variants("HEAD_DIM", "64, 128, 256, 512")]]
-[[Public]] [[Kernel]] func AttentionSinglePass<T, let HEAD_DIM: uint32_t>(
- StructuredBuffer<T> queries,
- StructuredBuffer<T> keys,
- StructuredBuffer<T> values,
- RWStructuredBuffer<T> out,
- uint32_t gqa_factor,
- uint32_t sequence_length,
- uint32_t k_head_stride,
- uint32_t k_seq_stride,
- uint32_t v_head_stride,
- uint32_t v_seq_stride,
- [[Optional("is_kv_cache_ring")]] RingParams ring_params,
- float scale,
- [[Optional("is_trie")]] StructuredBuffer<TrieNode> trie,
- [[Optional("is_sliding_window")]] uint32_t sliding_window_size,
- [[Optional("has_sinks")]] StructuredBuffer<T> sinks,
- uint32_t num_heads,
- uint32_t suffix_length,
- [[Specialize]] bool has_sinks,
- [[Specialize]] bool is_kv_cache_ring,
- [[Specialize]] bool is_causal,
- [[Specialize]] bool is_trie,
- [[Specialize]] bool is_sliding_window,
- ThreadContext thread_context,
- [[Groups("num_heads")]] uint32_t head_idx,
- [[Groups("suffix_length")]] uint32_t q_seq_idx,
- [[Threads("1024")]] uint32_t tid,
-) {
- // TODO
-}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang
index e4f4585f2..3ec2726de 100644
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang
@@ -2,19 +2,7 @@
import definitions;
import generated.kv_cache_update;
-[[Variants("T", "BFloat16")]]
-[[Public]] [[Kernel]] func KVCacheUpdate<T>(
- RWStructuredBuffer<T> in_place_keys,
- RWStructuredBuffer<T> in_place_values,
- [[Constant]] StructuredBuffer<Copy> copies,
- uint32_t copy_count,
- uint32_t element_dim,
- [[Axis("element_dim", "256")]] uint32_t element_idx,
-) {
- // TODO
-}
-
-[[Public]] [[Kernel]] func KVCacheUpdateInt8(
+[[Public]] [[Kernel]] func KVCacheUpdate(
RWStructuredBuffer<int8_t> in_place_k_codes,
RWStructuredBuffer<uint8_t> in_place_v_codes,
RWStructuredBuffer<BFloat16> in_place_k_scales,
@@ -23,6 +11,7 @@ import generated.kv_cache_update;
uint32_t copy_count,
[[Specialize]] uint32_t head_dim,
[[Specialize]] uint32_t num_kv_heads,
+ [[Specialize]] uint32_t backend_opaque_layout,
[[Axis("num_kv_heads* head_dim", "256")]] uint32_t element,
) {
// TODO
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/prepare.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/prepare.slang
new file mode 100644
index 000000000..941e907a9
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/prepare.slang
@@ -0,0 +1,40 @@
+// Autogenerated stub
+import definitions;
+import generated.qkv_norm;
+
+[[Variants("ElementT", "BFloat16, float")]]
+[[Variants("RopeT", "float")]]
+[[Variants("HEAD_DIM", "64, 128, 256, 512")]]
+[[Public]] [[Kernel]] func AttentionPrepare<ElementT, RopeT, let HEAD_DIM: uint32_t>(
+ StructuredBuffer<ElementT> qkvg,
+ RWStructuredBuffer<int8_t> q_codes,
+ RWStructuredBuffer<BFloat16> q_scales,
+ [[Optional("append_kv")]] RWStructuredBuffer<int8_t> k_codes,
+ [[Optional("append_kv")]] RWStructuredBuffer<BFloat16> k_scales,
+ [[Optional("append_kv")]] RWStructuredBuffer<uint8_t> v_codes,
+ [[Optional("append_kv")]] RWStructuredBuffer<BFloat16> v_scales,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> cosines,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> sines,
+ [[Optional("has_query_norm_scales")]] StructuredBuffer<float> query_norm_scales,
+ [[Optional("has_key_norm_scales")]] StructuredBuffer<float> key_norm_scales,
+ [[Optional("has_value_norm_scales")]] StructuredBuffer<float> value_norm_scales,
+ QKVNormParams norm_params,
+ uint32_t num_q_heads,
+ [[Optional("has_rope")]] uint32_t rope_dim,
+ uint32_t kv_token_offset,
+ uint32_t input_row_stride,
+ uint32_t suffix_length,
+ uint32_t query_rows,
+ [[Specialize]] bool has_rope,
+ [[Specialize]] uint32_t num_kv_heads,
+ [[Specialize]] uint32_t backend_opaque_layout,
+ [[Specialize]] bool append_kv,
+ [[Specialize]] bool has_query_norm_scales,
+ [[Specialize]] bool has_key_norm_scales,
+ [[Specialize]] bool has_value_norm_scales,
+ [[Groups("suffix_length")]] uint32_t token_idx,
+ [[Groups("num_q_heads + num_kv_heads * 2")]] uint32_t head_idx,
+ [[Threads("32")]] uint32_t lane,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang
deleted file mode 100644
index 7eb8f8626..000000000
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang
+++ /dev/null
@@ -1,33 +0,0 @@
-// Autogenerated stub
-import definitions;
-
-[[Variants("ElementT", "BFloat16")]]
-[[Variants("RopeT", "float")]]
-[[Variants("HEAD_DIM", "128, 256")]]
-[[Public]] [[Kernel]] func AttentionPrepareInt8<ElementT, RopeT, let HEAD_DIM: uint32_t>(
- StructuredBuffer<ElementT> qkvg,
- [[Optional("!quantize_queries")]] RWStructuredBuffer<ElementT> queries,
- [[Optional("quantize_queries")]] RWStructuredBuffer<int8_t> q_codes,
- [[Optional("quantize_queries")]] RWStructuredBuffer<ElementT> q_scales,
- [[Optional("append_kv")]] RWStructuredBuffer<int8_t> k_codes,
- [[Optional("append_kv")]] RWStructuredBuffer<ElementT> k_scales,
- [[Optional("append_kv")]] RWStructuredBuffer<uint8_t> v_codes,
- [[Optional("append_kv")]] RWStructuredBuffer<ElementT> v_scales,
- [[Optional("has_rope")]] StructuredBuffer<RopeT> cosines,
- [[Optional("has_rope")]] StructuredBuffer<RopeT> sines,
- uint32_t num_q_heads,
- [[Optional("has_rope")]] uint32_t rope_dim,
- uint32_t kv_token_offset,
- uint32_t input_row_stride,
- uint32_t suffix_length,
- uint32_t query_rows,
- [[Specialize]] bool has_rope,
- [[Specialize]] bool quantize_queries,
- [[Specialize]] uint32_t num_kv_heads,
- [[Specialize]] bool append_kv,
- [[Groups("suffix_length")]] uint32_t token_idx,
- [[Groups("num_q_heads + num_kv_heads * 2")]] uint32_t head_idx,
- [[Threads("32")]] uint32_t lane,
-) {
- // TODO
-}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang
deleted file mode 100644
index 92bd585ce..000000000
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang
+++ /dev/null
@@ -1,27 +0,0 @@
-// Autogenerated stub
-import definitions;
-
-[[Variants("InputT", "float, BFloat16")]]
-[[Variants("ScaleT", "float, BFloat16")]]
-[[Variants("OutputT", "float, BFloat16")]]
-[[Variants("AccumT", "float")]]
-[[Public]] [[Kernel]] func QKVNorm<InputT, ScaleT, OutputT, AccumT>(
- [[Optional("!in_place")]] StructuredBuffer<InputT> qkvg_input,
- [[Optional("has_scales")]] StructuredBuffer<ScaleT> scales,
- RWStructuredBuffer<OutputT> qkvg_output,
- uint32_t batch_size,
- uint32_t input_row_stride,
- uint32_t head_dim,
- float epsilon,
- float scale_offset,
- uint32_t head_offset,
- uint32_t head_count,
- bool full_layer,
- [[Groups("batch_size")]] uint32_t batch_idx,
- [[Groups("head_count")]] uint32_t head_idx,
- [[Threads("32")]] uint32_t lane_id,
- [[Specialize]] bool in_place,
- [[Specialize]] bool has_scales,
-) {
- // TODO
-}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang
deleted file mode 100644
index 4cdac646e..000000000
--- a/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang
+++ /dev/null
@@ -1,15 +0,0 @@
-// Autogenerated stub
-import definitions;
-
-[[Variants("T", "BFloat16")]]
-[[Public]] [[Kernel]] func SigmoidGate<T>(
- StructuredBuffer<T> gate,
- RWStructuredBuffer<T> output,
- uint32_t gate_dim,
- uint32_t batch_dim,
- uint32_t gate_row_stride,
- [[Axis("gate_dim", "256")]] uint32_t gate_idx,
- [[Axis("batch_dim", "1")]] uint32_t batch_idx,
-) {
- // TODO
-}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang
index 723611220..1893295fb 100644
--- a/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang
@@ -1,21 +1,5 @@
-static const uint TILE_KEYS = 32;
-
-static const uint TILE_QUERIES = 16;
-
-static const uint TILE_DIMS = 16;
-
-static const uint FRAGMENT_BYTES = TILE_KEYS * TILE_DIMS;
-
-static const uint SLICE_DIMS = 64;
-
static const int16_t V_CODE_BIAS = 128;
-static const uint GROUP_ROWS = 8;
-
-static const uint LANE_COLS = 4;
-
-static const uint LANE_BYTES = TILE_KEYS / GROUP_ROWS * LANE_COLS;
-
static const uint WORD_BITS = 32;
static const uint ROTATION_SIGN_BITS[8] = {2654435769, 2246822507, 3266489909, 668265263, 374761393, 3210233709, 2496678331, 3605593784};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/qkv_norm.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/qkv_norm.slang
new file mode 100644
index 000000000..b43ad47d0
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/qkv_norm.slang
@@ -0,0 +1,6 @@
+struct QKVNormParams {
+ uint enabled[3];
+ uint full_layer[3];
+ float epsilon[3];
+ float scale_offset[3];
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/webgpu/kernel.rs b/crates/uzu-engine/src/backends/webgpu/kernel.rs
index c13682325..c7c4a2129 100644
--- a/crates/uzu-engine/src/backends/webgpu/kernel.rs
+++ b/crates/uzu-engine/src/backends/webgpu/kernel.rs
@@ -4,6 +4,7 @@ use crate::{
Backend, BufferMut, BufferRef, CommandBufferEncoding, Kernels,
kernel::{
AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, Unsupported,
+ kv_layout::KVLayout,
matmul::{MatmulArguments, MatmulKernel},
radix_top_k_small::RadixTopKSmall,
},
@@ -33,6 +34,10 @@ impl AttentionKernel for Unsupported<WebGPU> {
type Backend = WebGPU;
type Error = WebGPUError;
+ fn kv_layout(&self) -> KVLayout {
+ unreachable!()
+ }
+
fn new(
_context: &WebGPUContext,
_config: AttentionKernelConfig,
diff --git a/crates/uzu-engine/src/encodable_block/dflash.rs b/crates/uzu-engine/src/encodable_block/dflash.rs
index 330c9c63c..b48d7b03c 100644
--- a/crates/uzu-engine/src/encodable_block/dflash.rs
+++ b/crates/uzu-engine/src/encodable_block/dflash.rs
@@ -268,7 +268,7 @@ impl<B: Backend> DFlash<B> {
);
}
}
- for ((layer, mixer_state), mut key_value) in
+ for ((layer, mixer_state), key_value) in
self.layers.iter().zip(state.layer_states.iter_mut()).zip(layer_key_values)
{
mixer_state.prepare(state.context_length, num_tokens).map_err(DFlashEncodeError::Backend)?;
@@ -279,7 +279,7 @@ impl<B: Backend> DFlash<B> {
.downcast_mut::<AttentionState<B>>()
.expect("DFlash draft layer states must be attention states");
attention
- .append_projected_kv(&mut key_value, &rope, num_tokens, attention_state, command_buffer)
+ .append_projected_kv(&key_value, &rope, num_tokens, attention_state, command_buffer)
.map_err(DFlashEncodeError::Backend)?;
}
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
deleted file mode 100644
index 9f477b782..000000000
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
+++ /dev/null
@@ -1,129 +0,0 @@
-use std::any::Any;
-
-use crate::{
- backends::common::{
- Backend, CommandBuffer, Context, DeviceCapabilities, GpuBuffer, Kernels, SparseBuffer,
- gpu_types::kv_cache_update::Copy,
- kernel::{KVCacheUpdateInt8Kernel, KVCacheUpdateKernel, KVFormat, kv_layout::Int8KVLayout},
- },
- data_type::DataType,
- utils::size_for_shape::size_for_shape,
-};
-
-pub enum KVStorage<B: Backend> {
- BF16(BF16KV<B>, <B::Kernels as Kernels>::KVCacheUpdateKernel),
- Int8(Int8KV<B>, <B::Kernels as Kernels>::KVCacheUpdateInt8Kernel),
-}
-
-pub struct BF16KV<B: Backend> {
- pub keys: Box<dyn GpuBuffer<Backend = B>>,
- pub values: Box<dyn GpuBuffer<Backend = B>>,
- pub element_dim: u32,
- pub data_type: DataType,
-}
-
-pub struct Int8KV<B: Backend> {
- pub layout: Int8KVLayout,
- pub k_codes: Box<dyn GpuBuffer<Backend = B>>,
- pub v_codes: Box<dyn GpuBuffer<Backend = B>>,
- pub k_scales: Box<dyn GpuBuffer<Backend = B>>,
- pub v_scales: Box<dyn GpuBuffer<Backend = B>>,
-}
-
-fn create_kv_buffer<B: Backend>(
- context: &B::Context,
- bytes: usize,
-) -> Result<Box<dyn GpuBuffer<Backend = B>>, B::Error> {
- Ok(if context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS) {
- Box::new(context.create_sparse_buffer(bytes)?)
- } else {
- Box::new(context.create_buffer_gpu(bytes)?)
- })
-}
-
-impl<B: Backend> KVStorage<B> {
- pub fn create_empty(
- format: KVFormat,
- num_kv_heads: u32,
- head_dim: u32,
- max_elements: u32,
- data_type: DataType,
- context: &B::Context,
- ) -> Result<Self, B::Error> {
- Ok(match format {
- KVFormat::INT8 => {
- let layout = Int8KVLayout::new(head_dim, num_kv_heads);
- let code_bytes = layout.code_bytes(max_elements);
- let scale_bytes = layout.scale_bytes(max_elements);
- let kv = Int8KV {
- k_codes: create_kv_buffer(context, code_bytes)?,
- v_codes: create_kv_buffer(context, code_bytes)?,
- k_scales: create_kv_buffer(context, scale_bytes)?,
- v_scales: create_kv_buffer(context, scale_bytes)?,
- layout,
- };
- Self::Int8(kv, <B::Kernels as Kernels>::KVCacheUpdateInt8Kernel::new(context, head_dim, num_kv_heads)?)
- },
- KVFormat::BF16 => {
- let element_dim = num_kv_heads * head_dim;
- let bytes = size_for_shape(&[max_elements, element_dim], data_type);
- let kv = BF16KV {
- keys: create_kv_buffer(context, bytes)?,
- values: create_kv_buffer(context, bytes)?,
- element_dim,
- data_type,
- };
- Self::BF16(kv, <B::Kernels as Kernels>::KVCacheUpdateKernel::new(context, data_type)?)
- },
- })
- }
-
- pub fn prepare(
- &mut self,
- elements_required: u32,
- ) -> Result<(), B::Error> {
- let map = |buffer: &mut dyn GpuBuffer<Backend = B>, bytes: usize| -> Result<(), B::Error> {
- match (buffer as &mut dyn Any).downcast_mut::<B::SparseBuffer>() {
- Some(sparse) => sparse.map(bytes),
- None => Ok(()),
- }
- };
- match self {
- Self::BF16(kv, _) => {
- let bytes = size_for_shape(&[elements_required, kv.element_dim], kv.data_type);
- map(kv.keys.as_mut(), bytes)?;
- map(kv.values.as_mut(), bytes)
- },
- Self::Int8(kv, _) => {
- let code_bytes = kv.layout.code_bytes(elements_required);
- map(kv.k_codes.as_mut(), code_bytes)?;
- map(kv.v_codes.as_mut(), code_bytes)?;
- let scale_bytes = kv.layout.scale_bytes(elements_required);
- map(kv.k_scales.as_mut(), scale_bytes)?;
- map(kv.v_scales.as_mut(), scale_bytes)
- },
- }
- }
-
- pub fn encode_accept(
- &mut self,
- copies: &[Copy],
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) {
- let count = copies.len() as u32;
- match self {
- Self::BF16(kv, update) => {
- update.encode(kv.keys.as_mut(), kv.values.as_mut(), copies, count, kv.element_dim, command_buffer)
- },
- Self::Int8(kv, update) => update.encode(
- kv.k_codes.as_mut(),
- kv.v_codes.as_mut(),
- kv.k_scales.as_mut(),
- kv.v_scales.as_mut(),
- copies,
- count,
- command_buffer,
- ),
- }
- }
-}
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
index d79e90bbf..fe1645245 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
@@ -3,33 +3,24 @@ use thiserror::Error;
use crate::{
backends::common::{
- Backend, CommandBuffer, CommandBufferEncoding, Kernels,
- kernel::{AttentionKernel, AttentionKernelConfig, AttentionPrepareInt8Kernel, AttentionPrepareKernel},
+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,
+ gpu_types::qkv_norm::QKVNormParams,
+ kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, AttentionPrepareKernel},
},
- config::{rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},
+ config::{normalization::UpcastMode, rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},
data_type::DataType,
encodable_block::{
batch_topology::BatchTopology,
linear::{Linear, LinearBlockError, LinearEncodeError},
- mixer::{
- Mixer, MixerEncodeError, MixerState,
- attention::{
- mode::LinearProjection,
- qkv_norm::{QKVNorm, QKVNormError},
- rope::PrecalculatedRoPE,
- },
- },
+ mixer::{Mixer, MixerEncodeError, MixerState, attention::rope::PrecalculatedRoPE},
},
safetensors::{ParameterLoaderError, ParameterTree},
utils::maybe_mut::MaybeMut,
};
-pub mod kv_storage;
-mod mode;
-mod qkv_norm;
mod state;
-pub use state::{ATTENTION_SUFFIX_CAPACITY, AttentionState, KVCacheView};
+pub use state::{ATTENTION_SUFFIX_CAPACITY, AttentionState, KVCache, KVCacheView};
pub mod rope;
@@ -43,9 +34,10 @@ pub struct Attention<B: Backend> {
data_type: DataType,
has_gate: bool,
projection_dim: u32,
- projection: LinearProjection<B>,
+ projection: Box<dyn Linear<B>>,
+ qkv_norm_params: QKVNormParams,
+ qkv_norm_scales: [Option<B::GlobalGpuBuffer>; 3],
prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,
- prepare_int8: Option<<B::Kernels as Kernels>::AttentionPrepareInt8Kernel>,
sinks: Option<B::GlobalGpuBuffer>,
kernel: <B::Kernels as Kernels>::AttentionKernel,
out_projection: Box<dyn Linear<B>>,
@@ -61,8 +53,6 @@ pub enum AttentionNewError<B: Backend> {
ParameterLoader(#[from] ParameterLoaderError<B>),
#[error("Linear error: {0}")]
Linear(#[from] LinearBlockError<B>),
- #[error("QKVNorm error: {0}")]
- QKVNorm(#[from] QKVNormError<B>),
}
#[derive(Debug, Error)]
@@ -123,28 +113,26 @@ impl<B: Backend> Attention<B> {
// TODO: Fix lalamo config, those two must be None if kv sharing.
let key_norm_config = (!is_kv_sharing).then(|| config.key_norm_config.clone()).flatten();
let value_norm_config = (!is_kv_sharing).then(|| config.value_norm_config()).flatten();
- let qkv_norm = QKVNorm::new(
- num_q_heads,
- num_kv_heads,
- projection_dim,
- head_dim,
- data_type,
- query_norm_config,
- key_norm_config,
- value_norm_config,
- parameter_tree,
- context,
- )
- .await?;
+ let mut qkv_norm_params = QKVNormParams::default();
+ let mut qkv_norm_scales = [None, None, None];
+ for (i, (config, name)) in
+ [(query_norm_config, "query_norm"), (key_norm_config, "key_norm"), (value_norm_config, "value_norm")]
+ .into_iter()
+ .enumerate()
+ {
+ let Some(config) = config else {
+ continue;
+ };
+ qkv_norm_params.enabled[i] = 1;
+ qkv_norm_params.full_layer[i] = u32::from(config.upcast_mode == UpcastMode::FullLayer);
+ qkv_norm_params.epsilon[i] = config.epsilon;
+ qkv_norm_params.scale_offset[i] = config.scale_offset.unwrap_or(0.0);
+ if config.has_scale {
+ qkv_norm_scales[i] =
+ Some(parameter_tree.subtree(name).read_buffer("scales", &[head_dim], DataType::F32).await?);
+ }
+ }
- let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
- context,
- data_type,
- DataType::F32,
- !is_kv_sharing,
- rope_config.is_some(),
- )
- .map_err(AttentionNewError::Backend)?;
let sinks = if config.has_sinks {
Some(parameter_tree.read_buffer("sinks", &[num_q_heads], data_type).await?)
} else {
@@ -171,22 +159,20 @@ impl<B: Backend> Attention<B> {
},
)
.map_err(AttentionNewError::Kernel)?;
- let prepare_int8 = kernel
- .supports_int8()
- .then(|| {
- <B::Kernels as Kernels>::AttentionPrepareInt8Kernel::new(
- context,
- data_type,
- DataType::F32,
- head_dim,
- rope_config.is_some(),
- true,
- num_groups,
- !is_kv_sharing,
- )
- })
- .transpose()
- .map_err(AttentionNewError::Backend)?;
+ let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ context,
+ data_type,
+ DataType::F32,
+ head_dim,
+ rope_config.is_some(),
+ num_groups,
+ kernel.kv_layout().backend_opaque_layout,
+ !is_kv_sharing,
+ qkv_norm_scales[0].is_some(),
+ qkv_norm_scales[1].is_some(),
+ qkv_norm_scales[2].is_some(),
+ )
+ .map_err(AttentionNewError::Backend)?;
let out_projection = <dyn Linear<B>>::new(
q_dim,
@@ -209,12 +195,10 @@ impl<B: Backend> Attention<B> {
data_type,
has_gate: config.has_gate,
projection_dim,
- projection: LinearProjection {
- lin: projection,
- norm: qkv_norm,
- },
+ projection,
+ qkv_norm_params,
+ qkv_norm_scales,
prepare,
- prepare_int8,
sinks,
kernel,
out_projection,
@@ -222,6 +206,155 @@ impl<B: Backend> Attention<B> {
in_projection_input_hadamard_factors,
))
}
+
+ fn attend(
+ &self,
+ hidden: B::ScratchBuffer,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<AttentionState<B>>>,
+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
+ ) -> Result<B::ScratchBuffer, AttentionEncodeError<B>> {
+ let qkvg = self.projection.encode(hidden, batch_dim.size(), command_buffer)?;
+ let gate = self.has_gate.then(|| {
+ qkvg.subrange(
+ (self.projection_dim - self.num_q_heads * self.head_dim) as usize * self.data_type.size_in_bytes()..,
+ )
+ });
+
+ let attention_output = {
+ let mut scratch_kv;
+ let (mut kv, cache) = match state {
+ Some(MaybeMut::Mut(state)) => {
+ let cache = state.view();
+ (MaybeMut::Mut(&mut state.kv), cache)
+ },
+ Some(MaybeMut::Const(state)) => (MaybeMut::Const(&state.kv), state.view()),
+ None => {
+ assert!(self.num_kv_heads.is_some(), "stateless query-only attention");
+ assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");
+ scratch_kv = KVCache::allocate_scratch(self.kernel.kv_layout(), batch_dim.size(), command_buffer)
+ .map_err(AttentionEncodeError::Backend)?;
+ let cache = self.ring_capacity.map_or_else(|| KVCacheView::full(0), |_| KVCacheView::ring(0, 0));
+ (MaybeMut::Mut(&mut scratch_kv), cache)
+ },
+ };
+ let (queries, query_scales) = self
+ .prepare(
+ &qkvg,
+ &mut kv,
+ cache.prefix_len(),
+ self.num_q_heads,
+ precalculated_rope,
+ batch_dim.size(),
+ command_buffer,
+ )
+ .map_err(AttentionEncodeError::Backend)?;
+ let input = AttentionInput {
+ query_codes: &queries,
+ query_scales: &query_scales,
+ k_codes: kv.k_codes.as_ref(),
+ k_scales: kv.k_scales.as_ref(),
+ v_codes: kv.v_codes.as_ref(),
+ v_scales: kv.v_scales.as_ref(),
+ };
+ let trie = (!batch_dim.is_flat())
+ .then(|| command_buffer.allocate_constant_from_slice(batch_dim.nodes()))
+ .transpose()
+ .map_err(AttentionEncodeError::Backend)?;
+ self.kernel
+ .encode(
+ input,
+ AttentionArguments {
+ suffix_length: batch_dim.size(),
+ trie: trie.as_ref(),
+ sinks: self.sinks.as_ref(),
+ cache,
+ gate,
+ },
+ command_buffer,
+ )
+ .map_err(AttentionEncodeError::Kernel)?
+ };
+
+ Ok(self.out_projection.encode(attention_output, batch_dim.size(), command_buffer)?)
+ }
+
+ pub fn append_projected_kv(
+ &self,
+ key_value: impl BufferRef<Backend = B>,
+ precalculated_rope: &PrecalculatedRoPE<B>,
+ batch_dim: u32,
+ state: &mut AttentionState<B>,
+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
+ ) -> Result<(), B::Error> {
+ let prefix_len = state.view().prefix_len();
+ self.prepare(
+ key_value,
+ &mut MaybeMut::Mut(&mut state.kv),
+ prefix_len,
+ 0,
+ Some(precalculated_rope),
+ batch_dim,
+ command_buffer,
+ )?;
+ state.encode_accept(&(0..batch_dim).collect::<Box<[u32]>>(), command_buffer)?;
+ Ok(())
+ }
+
+ fn prepare(
+ &self,
+ qkvg: impl BufferRef<Backend = B>,
+ kv: &mut MaybeMut<'_, KVCache<B>>,
+ kv_token_offset: u32,
+ num_q_heads: u32,
+ rope: Option<&PrecalculatedRoPE<B>>,
+ suffix_length: u32,
+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
+ ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {
+ assert_eq!(kv.layout, self.kernel.kv_layout(), "shared KV layout mismatch");
+ let (k_codes, k_scales, v_codes, v_scales) = match kv {
+ MaybeMut::Mut(kv) => (
+ Some(kv.k_codes.as_mut()),
+ Some(kv.k_scales.as_mut()),
+ Some(kv.v_codes.as_mut()),
+ Some(kv.v_scales.as_mut()),
+ ),
+ MaybeMut::Const(_) => (None, None, None, None),
+ };
+ let input_row_stride = if num_q_heads == 0 {
+ 2 * self.num_groups * self.head_dim
+ } else {
+ self.projection_dim
+ };
+ let query_count = num_q_heads as usize * suffix_length as usize;
+ // K/V-only calls still need bound query buffers.
+ let mut query_codes = command_buffer.allocate_scratch((query_count * self.head_dim as usize).max(1))?;
+ let mut query_scales = command_buffer.allocate_scratch(query_count.max(1) * DataType::BF16.size_in_bytes())?;
+ self.prepare.encode(
+ qkvg,
+ &mut query_codes,
+ &mut query_scales,
+ k_codes,
+ k_scales,
+ v_codes,
+ v_scales,
+ rope.map(|rope| &rope.cosines),
+ rope.map(|rope| &rope.sines),
+ self.qkv_norm_scales[0].as_ref(),
+ self.qkv_norm_scales[1].as_ref(),
+ self.qkv_norm_scales[2].as_ref(),
+ self.qkv_norm_params,
+ num_q_heads,
+ rope.map(|rope| rope.dim),
+ kv_token_offset,
+ input_row_stride,
+ suffix_length,
+ num_q_heads / self.num_groups * suffix_length,
+ command_buffer,
+ );
+ Ok((query_codes, query_scales))
+ }
}
impl<B: Backend> Mixer<B> for Attention<B> {
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
deleted file mode 100644
index b3d03b2cf..000000000
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
+++ /dev/null
@@ -1,312 +0,0 @@
-use crate::{
- backends::common::{
- Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, GpuBuffer,
- kernel::{
- AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareInt8Kernel, AttentionPrepareKernel,
- FullPrecisionInput, Int8Input,
- },
- },
- data_type::DataType,
- encodable_block::{
- batch_topology::BatchTopology,
- linear::Linear,
- mixer::{
- MixerState,
- attention::{
- Attention, AttentionEncodeError, KVCacheView,
- kv_storage::{Int8KV, KVStorage},
- qkv_norm::QKVNorm,
- rope::PrecalculatedRoPE,
- state::AttentionState,
- },
- },
- },
- utils::maybe_mut::MaybeMut,
-};
-
-enum KVBuffers<'a, B: Backend> {
- BF16 {
- keys: MaybeMut<'a, dyn GpuBuffer<Backend = B>>,
- values: MaybeMut<'a, dyn GpuBuffer<Backend = B>>,
- },
- Int8(MaybeMut<'a, Int8KV<B>>),
-}
-
-pub(super) struct LinearProjection<B: Backend> {
- pub(super) lin: Box<dyn Linear<B>>,
- pub(super) norm: QKVNorm<B>,
-}
-
-impl<B: Backend> LinearProjection<B> {
- fn project(
- &self,
- hidden: B::ScratchBuffer,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, AttentionEncodeError<B>> {
- let mut projected = self.lin.encode(hidden, batch_dim, command_buffer)?;
- self.norm.encode(&mut projected, batch_dim, command_buffer);
- Ok(projected)
- }
-}
-
-impl<B: Backend> Attention<B> {
- pub(super) fn attend(
- &self,
- hidden: B::ScratchBuffer,
- precalculated_rope: Option<&PrecalculatedRoPE<B>>,
- batch_dim: &BatchTopology,
- state: Option<MaybeMut<AttentionState<B>>>,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, AttentionEncodeError<B>> {
- let qkvg = self.projection.project(hidden, batch_dim.size(), command_buffer)?;
- let gate = self.has_gate.then(|| {
- qkvg.subrange(
- (self.projection_dim - self.num_q_heads * self.head_dim) as usize * self.data_type.size_in_bytes()..,
- )
- });
-
- let attention_output = {
- let (mut keys, mut values);
- let (mut kv, cache) = match state {
- Some(MaybeMut::Mut(state)) => {
- let cache = state.view();
- let kv = match &mut state.kv {
- KVStorage::BF16(kv, _) => KVBuffers::BF16 {
- keys: MaybeMut::Mut(kv.keys.as_mut()),
- values: MaybeMut::Mut(kv.values.as_mut()),
- },
- KVStorage::Int8(kv, _) => KVBuffers::Int8(MaybeMut::Mut(kv)),
- };
- (kv, cache)
- },
- Some(MaybeMut::Const(state)) => {
- let kv = match &state.kv {
- KVStorage::BF16(kv, _) => KVBuffers::BF16 {
- keys: MaybeMut::Const(kv.keys.as_ref()),
- values: MaybeMut::Const(kv.values.as_ref()),
- },
- KVStorage::Int8(kv, _) => KVBuffers::Int8(MaybeMut::Const(kv)),
- };
- (kv, state.view())
- },
- None => {
- let Some(num_kv_heads) = self.num_kv_heads else {
- panic!("stateless attention doesn't support query-only projection");
- };
- assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");
-
- keys = command_buffer
- .allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)
- .map_err(AttentionEncodeError::Backend)?;
- values = command_buffer
- .allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)
- .map_err(AttentionEncodeError::Backend)?;
- let kv = KVBuffers::BF16 {
- keys: MaybeMut::Mut(&mut keys),
- values: MaybeMut::Mut(&mut values),
- };
- let cache = self.ring_capacity.map_or_else(|| KVCacheView::full(0), |_| KVCacheView::ring(0, 0));
- (kv, cache)
- },
- };
- let (queries, query_scales);
- let input = match &mut kv {
- KVBuffers::BF16 {
- keys,
- values,
- } => {
- queries = self
- .prepare_bf16(
- &qkvg,
- keys,
- values,
- cache.prefix_len(),
- self.num_q_heads,
- precalculated_rope,
- batch_dim.size(),
- command_buffer,
- )
- .map_err(AttentionEncodeError::Backend)?;
- AttentionInput::FullPrecision(FullPrecisionInput {
- queries: &queries,
- keys: &**keys,
- values: &**values,
- })
- },
- KVBuffers::Int8(kv) => {
- (queries, query_scales) = self
- .prepare_int8(
- &qkvg,
- kv,
- cache.prefix_len(),
- self.num_q_heads,
- precalculated_rope,
- batch_dim.size(),
- command_buffer,
- )
- .map_err(AttentionEncodeError::Backend)?;
- AttentionInput::Int8(Int8Input {
- query_codes: &queries,
- query_scales: &query_scales,
- k_codes: kv.k_codes.as_ref(),
- k_scales: kv.k_scales.as_ref(),
- v_codes: kv.v_codes.as_ref(),
- v_scales: kv.v_scales.as_ref(),
- })
- },
- };
- let trie = (!batch_dim.is_flat())
- .then(|| command_buffer.allocate_constant_from_slice(batch_dim.nodes()))
- .transpose()
- .map_err(AttentionEncodeError::Backend)?;
- self.kernel
- .encode(
- input,
- AttentionArguments {
- suffix_length: batch_dim.size(),
- trie: trie.as_ref(),
- sinks: self.sinks.as_ref(),
- cache,
- gate,
- },
- command_buffer,
- )
- .map_err(AttentionEncodeError::Kernel)?
- };
-
- Ok(self.out_projection.encode(attention_output, batch_dim.size(), command_buffer)?)
- }
-
- pub fn append_projected_kv(
- &self,
- mut key_value: impl BufferMut<Backend = B>,
- precalculated_rope: &PrecalculatedRoPE<B>,
- batch_dim: u32,
- state: &mut AttentionState<B>,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<(), B::Error> {
- self.projection.norm.encode_key_value(key_value.reborrow(), batch_dim, command_buffer);
- let prefix_len = state.view().prefix_len();
- match &mut state.kv {
- KVStorage::BF16(kv, _) => {
- self.prepare_bf16(
- key_value.as_ref(),
- &mut MaybeMut::Mut(kv.keys.as_mut()),
- &mut MaybeMut::Mut(kv.values.as_mut()),
- prefix_len,
- 0,
- Some(precalculated_rope),
- batch_dim,
- command_buffer,
- )?;
- },
- KVStorage::Int8(kv, _) => {
- self.prepare_int8(
- key_value.as_ref(),
- &mut MaybeMut::Mut(kv),
- prefix_len,
- 0,
- Some(precalculated_rope),
- batch_dim,
- command_buffer,
- )?;
- },
- }
- state.encode_accept(&(0..batch_dim).collect::<Box<[u32]>>(), command_buffer)?;
- Ok(())
- }
-
- fn prepare_bf16(
- &self,
- qkvg: impl BufferRef<Backend = B>,
- keys: &mut MaybeMut<'_, dyn GpuBuffer<Backend = B>>,
- values: &mut MaybeMut<'_, dyn GpuBuffer<Backend = B>>,
- kv_token_offset: u32,
- num_q_heads: u32,
- rope: Option<&PrecalculatedRoPE<B>>,
- suffix_length: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error> {
- let (output_keys, output_values) = match (keys, values) {
- (MaybeMut::Mut(keys), MaybeMut::Mut(values)) => (Some(&mut **keys), Some(&mut **values)),
- _ => (None, None),
- };
- let append_kv = output_keys.is_some();
- let input_row_stride = if num_q_heads == 0 {
- 2 * self.num_groups * self.head_dim
- } else {
- self.projection_dim
- };
- let query_count = num_q_heads as usize * suffix_length as usize;
- let mut queries = command_buffer
- .allocate_scratch((query_count * self.head_dim as usize).max(1) * self.data_type.size_in_bytes())?;
- self.prepare.encode(
- qkvg,
- &mut queries,
- output_keys,
- output_values,
- rope.map(|rope| &rope.cosines),
- rope.map(|rope| &rope.sines),
- num_q_heads,
- append_kv.then_some(self.num_groups),
- self.head_dim,
- rope.map(|rope| rope.dim),
- append_kv.then_some(kv_token_offset),
- input_row_stride,
- suffix_length,
- command_buffer,
- );
- Ok(queries)
- }
-
- fn prepare_int8(
- &self,
- qkvg: impl BufferRef<Backend = B>,
- kv: &mut MaybeMut<'_, Int8KV<B>>,
- kv_token_offset: u32,
- num_q_heads: u32,
- rope: Option<&PrecalculatedRoPE<B>>,
- suffix_length: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {
- let (k_codes, k_scales, v_codes, v_scales) = match kv {
- MaybeMut::Mut(kv) => (
- Some(kv.k_codes.as_mut()),
- Some(kv.k_scales.as_mut()),
- Some(kv.v_codes.as_mut()),
- Some(kv.v_scales.as_mut()),
- ),
- MaybeMut::Const(_) => (None, None, None, None),
- };
- let input_row_stride = if num_q_heads == 0 {
- 2 * self.num_groups * self.head_dim
- } else {
- self.projection_dim
- };
- let query_count = num_q_heads as usize * suffix_length as usize;
- // K/V-only calls still need bound query buffers.
- let mut query_codes = command_buffer.allocate_scratch((query_count * self.head_dim as usize).max(1))?;
- let mut query_scales = command_buffer.allocate_scratch(query_count.max(1) * DataType::BF16.size_in_bytes())?;
- self.prepare_int8.as_ref().expect("INT8 prepare kernel").encode(
- qkvg,
- None::<&mut B::ScratchBuffer>,
- Some(&mut query_codes),
- Some(&mut query_scales),
- k_codes,
- k_scales,
- v_codes,
- v_scales,
- rope.map(|rope| &rope.cosines),
- rope.map(|rope| &rope.sines),
- num_q_heads,
- rope.map(|rope| rope.dim),
- kv_token_offset,
- input_row_stride,
- suffix_length,
- num_q_heads / self.num_groups * suffix_length,
- command_buffer,
- );
- Ok((query_codes, query_scales))
- }
-}
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
deleted file mode 100644
index 7cc46a84f..000000000
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
+++ /dev/null
@@ -1,158 +0,0 @@
-use derive_more::Debug;
-use thiserror::Error;
-
-use crate::{
- backends::common::{
- Backend, BufferMut, CommandBuffer,
- kernel::{Kernels, QKVNormKernel},
- },
- config::normalization::{NormalizationConfig, UpcastMode},
- data_type::DataType,
- safetensors::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum QKVNormError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Parameter loading error: {0}")]
- ParameterError(#[from] ParameterLoaderError<B>),
-}
-
-struct Head<B: Backend> {
- kernel: <B::Kernels as Kernels>::QKVNormKernel,
- scales: Option<B::GlobalGpuBuffer>,
- config: NormalizationConfig,
-}
-
-pub struct QKVNorm<B: Backend> {
- query: Option<Head<B>>,
- key: Option<Head<B>>,
- value: Option<Head<B>>,
- num_q_heads: u32,
- num_kv_heads: Option<u32>,
- projection_row_stride: u32,
- head_dim: u32,
-}
-
-impl<B: Backend> QKVNorm<B> {
- pub async fn new(
- num_q_heads: u32,
- num_kv_heads: Option<u32>,
- projection_row_stride: u32,
- head_dim: u32,
- intermediate_data_type: DataType,
- query_config: Option<NormalizationConfig>,
- key_config: Option<NormalizationConfig>,
- value_config: Option<NormalizationConfig>,
- parameter_tree: &ParameterTree<'_, B>,
- context: &B::Context,
- ) -> Result<Self, QKVNormError<B>> {
- let build_head = async |config: Option<NormalizationConfig>, parameter_name: Option<&str>| {
- let Some(config) = config else {
- return Ok::<_, QKVNormError<B>>(None);
- };
- let scales = if config.has_scale {
- Some(
- parameter_tree
- .subtree(parameter_name.expect("scaled norm requires parameter tree"))
- .read_buffer("scales", &[head_dim], DataType::F32)
- .await?,
- )
- } else {
- None
- };
- let kernel = <B::Kernels as Kernels>::QKVNormKernel::new(
- context,
- intermediate_data_type,
- DataType::F32,
- intermediate_data_type,
- DataType::F32,
- true,
- scales.is_some(),
- )
- .map_err(QKVNormError::BackendError)?;
- Ok(Some(Head {
- kernel,
- scales,
- config,
- }))
- };
-
- let query = build_head(query_config, Some("query_norm")).await?;
- let key = build_head(key_config, Some("key_norm")).await?;
- let value = build_head(value_config, None).await?;
- Ok(Self {
- query,
- key,
- value,
- num_q_heads,
- num_kv_heads,
- projection_row_stride,
- head_dim,
- })
- }
-
- pub fn encode(
- &self,
- qkvg: impl BufferMut<Backend = B>,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) {
- self.encode_packed(qkvg, batch_dim, self.num_q_heads, self.projection_row_stride, command_buffer)
- }
-
- pub fn encode_key_value(
- &self,
- key_value: impl BufferMut<Backend = B>,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) {
- let num_kv_heads = self.num_kv_heads.expect("KV norm requires KV heads");
- self.encode_packed(key_value, batch_dim, 0, 2 * num_kv_heads * self.head_dim, command_buffer)
- }
-
- fn encode_packed(
- &self,
- mut buffer: impl BufferMut<Backend = B>,
- batch_dim: u32,
- q_heads: u32,
- input_row_stride: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) {
- let kv = self.num_kv_heads.unwrap_or(0);
- let packed_row_width = (q_heads + 2 * kv) * self.head_dim;
- assert!(
- input_row_stride >= packed_row_width,
- "QKV norm input row stride ({input_row_stride}) is smaller than its packed row width ({packed_row_width})"
- );
-
- let heads = [(&self.query, 0, q_heads), (&self.key, q_heads, kv), (&self.value, q_heads + kv, kv)];
- for (head, head_offset, head_count) in heads {
- let Some(head) = head else {
- continue;
- };
- if head_count == 0 {
- continue;
- }
- head.kernel.encode(
- None::<&B::ScratchBuffer>,
- head.scales.as_ref(),
- buffer.reborrow(),
- batch_dim,
- input_row_stride,
- self.head_dim,
- head.config.epsilon,
- head.config.scale_offset.unwrap_or(0.0),
- head_offset,
- head_count,
- head.config.upcast_mode == UpcastMode::FullLayer,
- command_buffer,
- );
- }
- }
-}
-
-#[cfg(test)]
-#[path = "../../../../unit/encodable_block/attention/qkv_norm_test.rs"]
-mod tests;
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
index 31e4b23fa..d43516852 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
@@ -1,13 +1,12 @@
+use std::any::Any;
+
use crate::{
backends::common::{
- Backend, CommandBuffer,
+ Backend, CommandBuffer, CommandBufferEncoding, Context, DeviceCapabilities, GpuBuffer, Kernels, SparseBuffer,
gpu_types::{kv_cache_update::Copy, ring::RingParams},
- kernel::{AttentionKernel, KVFormat},
- },
- encodable_block::mixer::{
- MixerState,
- attention::{Attention, kv_storage::KVStorage},
+ kernel::{AttentionKernel, KVCacheUpdateKernel, kv_layout::KVLayout},
},
+ encodable_block::mixer::{MixerState, attention::Attention},
};
pub const ATTENTION_SUFFIX_CAPACITY: u32 = 1024; // TODO: remove hardcoded suffix capacity
@@ -159,9 +158,34 @@ impl KVCacheState {
}
}
+pub struct KVCache<B: Backend> {
+ pub layout: KVLayout,
+ pub k_codes: Box<dyn GpuBuffer<Backend = B>>,
+ pub v_codes: Box<dyn GpuBuffer<Backend = B>>,
+ pub k_scales: Box<dyn GpuBuffer<Backend = B>>,
+ pub v_scales: Box<dyn GpuBuffer<Backend = B>>,
+}
+
+impl<B: Backend> KVCache<B> {
+ pub fn allocate_scratch(
+ layout: KVLayout,
+ max_elements: u32,
+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
+ ) -> Result<Self, B::Error> {
+ Ok(Self {
+ k_codes: Box::new(command_buffer.allocate_scratch(layout.code_bytes(max_elements))?),
+ v_codes: Box::new(command_buffer.allocate_scratch(layout.code_bytes(max_elements))?),
+ k_scales: Box::new(command_buffer.allocate_scratch(layout.scale_bytes(max_elements))?),
+ v_scales: Box::new(command_buffer.allocate_scratch(layout.scale_bytes(max_elements))?),
+ layout,
+ })
+ }
+}
+
pub struct AttentionState<B: Backend> {
cache: KVCacheState,
- pub kv: KVStorage<B>,
+ pub kv: KVCache<B>,
+ kv_cache_update: <B::Kernels as Kernels>::KVCacheUpdateKernel,
}
impl<B: Backend> AttentionState<B> {
@@ -189,23 +213,37 @@ impl<B: Backend> AttentionState<B> {
let cache = attention.ring_capacity.map_or_else(KVCacheState::full, KVCacheState::ring);
- let format = if attention.kernel.supports_int8() {
- KVFormat::INT8
- } else {
- KVFormat::BF16
+ let num_kv_heads = attention.num_kv_heads.unwrap();
+ let head_dim = attention.head_dim;
+ let layout = attention.kernel.kv_layout();
+ let max_elements = max_prefix_elements + ATTENTION_SUFFIX_CAPACITY;
+ let code_bytes = layout.code_bytes(max_elements);
+ let scale_bytes = layout.scale_bytes(max_elements);
+ let allocate = |bytes| -> Result<Box<dyn GpuBuffer<Backend = B>>, B::Error> {
+ Ok(if context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS) {
+ Box::new(context.create_sparse_buffer(bytes)?)
+ } else {
+ Box::new(context.create_buffer_gpu(bytes)?)
+ })
};
- let kv = KVStorage::create_empty(
- format,
- attention.num_kv_heads.unwrap(),
- attention.head_dim,
- max_prefix_elements + ATTENTION_SUFFIX_CAPACITY,
- attention.data_type,
+ let kv = KVCache {
+ k_codes: allocate(code_bytes)?,
+ v_codes: allocate(code_bytes)?,
+ k_scales: allocate(scale_bytes)?,
+ v_scales: allocate(scale_bytes)?,
+ layout,
+ };
+ let kv_cache_update = <B::Kernels as Kernels>::KVCacheUpdateKernel::new(
context,
+ head_dim,
+ num_kv_heads,
+ layout.backend_opaque_layout,
)?;
Ok(Self {
cache,
kv,
+ kv_cache_update,
})
}
}
@@ -218,7 +256,19 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {
) -> Result<(), B::Error> {
assert!(suffix_length <= ATTENTION_SUFFIX_CAPACITY, "suffix exceeds capacity");
- self.kv.prepare(self.cache.required_prefix_len(context_length) + suffix_length)
+ let map = |buffer: &mut dyn GpuBuffer<Backend = B>, bytes: usize| -> Result<(), B::Error> {
+ match (buffer as &mut dyn Any).downcast_mut::<B::SparseBuffer>() {
+ Some(sparse) => sparse.map(bytes),
+ None => Ok(()),
+ }
+ };
+ let elements_required = self.cache.required_prefix_len(context_length) + suffix_length;
+ let code_bytes = self.kv.layout.code_bytes(elements_required);
+ let scale_bytes = self.kv.layout.scale_bytes(elements_required);
+ map(self.kv.k_codes.as_mut(), code_bytes)?;
+ map(self.kv.v_codes.as_mut(), code_bytes)?;
+ map(self.kv.k_scales.as_mut(), scale_bytes)?;
+ map(self.kv.v_scales.as_mut(), scale_bytes)
}
fn encode_accept(
@@ -229,7 +279,15 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {
let copies = self.cache.accept(accepted_indices);
if !copies.is_empty() {
- self.kv.encode_accept(&copies, command_buffer);
+ self.kv_cache_update.encode(
+ self.kv.k_codes.as_mut(),
+ self.kv.v_codes.as_mut(),
+ self.kv.k_scales.as_mut(),
+ self.kv.v_scales.as_mut(),
+ &copies,
+ copies.len() as u32,
+ command_buffer,
+ );
}
Ok(())
diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rs
index 797de15aa..67776e039 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -12,7 +12,7 @@ use crate::{
},
kernel::{
ActivationTransform, AncestorAttentionKernel, AttentionArguments, AttentionInput, AttentionKernel,
- FullPrecisionInput, WeaverSelectKernel, radix_top_k_small::RadixTopKSmall,
+ WeaverSelectKernel, radix_top_k_small::RadixTopKSmall,
},
},
config::{rope::AnyRoPEConfig, weaver::WeaverConfig},
@@ -20,7 +20,7 @@ use crate::{
encodable_block::{
embedding::{Embedding, EmbeddingError},
linear::{Linear, LinearBlockError, LinearEncodeError, RHTLinearWrapper},
- mixer::attention::{KVCacheView, rope::PrecalculatedRoPE},
+ mixer::attention::{KVCache, KVCacheView, rope::PrecalculatedRoPE},
mlp::{MlpBlockNewError, MlpEncodeError},
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
weaver_layer::{PreparedPrefixAttention, WeaverLayer},
@@ -362,7 +362,7 @@ impl<B: Backend> Weaver<B> {
rope: &PrecalculatedRoPE<B>,
depth: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<Vec<B::ScratchBuffer>, WeaverEncodeError<B>> {
+ ) -> Result<Vec<KVCache<B>>, WeaverEncodeError<B>> {
let command_buffer = &mut *command_buffer.debug_group("weaver prefix");
let hidden_row_bytes = size_for_shape(&[self.target_model_dim], DATA_TYPE);
@@ -396,19 +396,22 @@ impl<B: Backend> Weaver<B> {
let mut prefix_kv_layers = Vec::with_capacity(self.layers.len());
for layer in preceding_layers {
let PreparedPrefixAttention {
- queries,
+ query_codes,
+ query_scales,
kv_cache,
} = layer.encode_prefix_attention(&residual_input, &mut residual_state, rope, depth, command_buffer)?;
let cache = KVCacheView::full(0);
- let kv_plane_bytes = size_for_shape(&[depth, self.model_dim], DATA_TYPE);
let attention_output = layer
.prefix_attention
.encode(
- AttentionInput::FullPrecision(FullPrecisionInput {
- queries: &queries,
- keys: &kv_cache,
- values: kv_cache.subrange(kv_plane_bytes..),
- }),
+ AttentionInput {
+ query_codes: &query_codes,
+ query_scales: &query_scales,
+ k_codes: kv_cache.k_codes.as_ref(),
+ k_scales: kv_cache.k_scales.as_ref(),
+ v_codes: kv_cache.v_codes.as_ref(),
+ v_scales: kv_cache.v_scales.as_ref(),
+ },
AttentionArguments {
suffix_length: depth,
trie: None::<&B::ConstantBuffer>,
@@ -432,12 +435,12 @@ impl<B: Backend> Weaver<B> {
Ok(prefix_kv_layers)
}
- fn encode_step<Ids: BufferRef<Backend = B>, Logits: BufferRef<Backend = B>>(
+ fn encode_step<'a, Ids: BufferRef<Backend = B>, Logits: BufferRef<Backend = B>>(
&self,
target_embedding: &Embedding<B>,
- mut prefix_kv_layers: impl Iterator<Item = impl BufferRef<Backend = B>>,
+ mut prefix_kv_layers: impl Iterator<Item = &'a KVCache<B>>,
rope: &PrecalculatedRoPE<B>,
- mut node_kv_layers: impl Iterator<Item = impl BufferMut<Backend = B>>,
+ mut node_kv_layers: impl Iterator<Item = &'a mut KVCache<B>>,
mut packed_tree: impl BufferMut<Backend = B>,
mut frontier: impl BufferMut<Backend = B>,
mut slot_ancestors: impl BufferMut<Backend = B>,
@@ -520,9 +523,17 @@ impl<B: Backend> Weaver<B> {
let mut attention_output = command_buffer
.allocate_scratch_for_shape(&[batch_node_count, self.model_dim], DATA_TYPE)
.map_err(WeaverEncodeError::Backend)?;
+ let prefix_kv = prefix_kv_layers.next().expect("missing prefix KV layer");
+ let node_kv = node_kv_layers.next().expect("missing node KV layer");
layer.ancestor_attention.encode(
- prefix_kv_layers.next().expect("missing prefix KV layer"),
- node_kv_layers.next().expect("missing node KV layer"),
+ prefix_kv.k_codes.as_ref(),
+ prefix_kv.k_scales.as_ref(),
+ prefix_kv.v_codes.as_ref(),
+ prefix_kv.v_scales.as_ref(),
+ node_kv.k_codes.as_mut(),
+ node_kv.k_scales.as_mut(),
+ node_kv.v_codes.as_mut(),
+ node_kv.v_scales.as_mut(),
&current_qkv,
&rope.cosines,
&rope.sines,
@@ -669,9 +680,9 @@ impl<B: Backend> Weaver<B> {
self.encode_prefix(target_hidden, draft_hidden, &rope, shape.dflash_depth, command_buffer)?;
// Per-layer KV cache for tree nodes, one slot per packed-tree slot.
- let node_kv_size = size_for_shape(&[2, tree_slot_count, self.model_dim], DATA_TYPE);
- let mut node_kv_layers = (0..self.layers.len())
- .map(|_| command_buffer.allocate_scratch(node_kv_size))
+ let mut node_kv_layers = prefix_kv_layers
+ .iter()
+ .map(|prefix| KVCache::allocate_scratch(prefix.layout, tree_slot_count, command_buffer))
.collect::<Result<Vec<_>, _>>()
.map_err(WeaverEncodeError::Backend)?;
diff --git a/crates/uzu-engine/src/encodable_block/weaver_layer.rs b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
index d05900b46..9af848cff 100644
--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
@@ -10,18 +10,18 @@ use crate::{
},
encodable_block::{
linear::Linear,
- mixer::attention::rope::PrecalculatedRoPE,
+ mixer::attention::{KVCache, rope::PrecalculatedRoPE},
mlp::Mlp,
normalization::{Normalization, PostLayerScalar, ShortcutMode},
weaver::{DATA_TYPE, ROPE_DATA_TYPE, WeaverEncodeError, WeaverNewError},
},
safetensors::ParameterTree,
- utils::size_for_shape::size_for_shape,
};
pub struct PreparedPrefixAttention<B: Backend> {
- pub queries: B::ScratchBuffer,
- pub kv_cache: B::ScratchBuffer,
+ pub query_codes: B::ScratchBuffer,
+ pub query_scales: B::ScratchBuffer,
+ pub kv_cache: KVCache<B>,
}
pub struct WeaverLayer<B: Backend> {
@@ -36,7 +36,6 @@ pub struct WeaverLayer<B: Backend> {
pub attention_scale: f32,
model_dim: u32,
num_heads: u32,
- head_dim: u32,
pub max_depth: u32,
}
@@ -92,9 +91,20 @@ impl<B: Backend> WeaverLayer<B> {
},
)
.map_err(WeaverNewError::Attention)?;
- let attention_prepare =
- <B::Kernels as Kernels>::AttentionPrepareKernel::new(context, DATA_TYPE, ROPE_DATA_TYPE, true, true)
- .map_err(WeaverNewError::Backend)?;
+ let attention_prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ context,
+ DATA_TYPE,
+ ROPE_DATA_TYPE,
+ head_dim,
+ true,
+ num_heads,
+ prefix_attention.kv_layout().backend_opaque_layout,
+ true,
+ false,
+ false,
+ false,
+ )
+ .map_err(WeaverNewError::Backend)?;
let pre_attention_norm = Normalization::new(
model_dim,
DATA_TYPE,
@@ -133,8 +143,13 @@ impl<B: Backend> WeaverLayer<B> {
<dyn Mlp<B>>::new(model_dim, hidden_dim, DATA_TYPE, &mlp_config, &parameter_tree.subtree("mlp"), context)
.await?;
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, num_heads)
- .map_err(WeaverNewError::Backend)?;
+ let ancestor_attention = <B::Kernels as Kernels>::AncestorAttentionKernel::new(
+ context,
+ head_dim,
+ num_heads,
+ prefix_attention.kv_layout().backend_opaque_layout,
+ )
+ .map_err(WeaverNewError::Backend)?;
Ok(Self {
qkv_projection,
out_projection,
@@ -147,7 +162,6 @@ impl<B: Backend> WeaverLayer<B> {
attention_scale,
model_dim,
num_heads,
- head_dim,
max_depth,
})
}
@@ -165,32 +179,39 @@ impl<B: Backend> WeaverLayer<B> {
.encode(residual_input, 0, token_count, Some(residual_state), command_buffer)
.map_err(WeaverEncodeError::Backend)?;
let qkv = self.qkv_projection.encode(input, token_count, command_buffer)?;
- let mut queries = command_buffer
- .allocate_scratch_for_shape(&[self.num_heads, token_count, self.head_dim], DATA_TYPE)
+ let mut query_codes = command_buffer
+ .allocate_scratch((token_count * self.model_dim) as usize)
.map_err(WeaverEncodeError::Backend)?;
- let kv_plane_bytes = size_for_shape(&[token_count, self.model_dim], DATA_TYPE);
- let mut kv_cache = command_buffer
- .allocate_scratch_for_shape(&[2, token_count, self.model_dim], DATA_TYPE)
+ let mut query_scales = command_buffer
+ .allocate_scratch_for_shape(&[token_count, self.num_heads], DATA_TYPE)
+ .map_err(WeaverEncodeError::Backend)?;
+ let mut kv_cache = KVCache::allocate_scratch(self.prefix_attention.kv_layout(), token_count, command_buffer)
.map_err(WeaverEncodeError::Backend)?;
- let (keys, values) = kv_cache.split_at(kv_plane_bytes);
self.attention_prepare.encode(
&qkv,
- &mut queries,
- Some(keys),
- Some(values),
+ &mut query_codes,
+ &mut query_scales,
+ Some(kv_cache.k_codes.as_mut()),
+ Some(kv_cache.k_scales.as_mut()),
+ Some(kv_cache.v_codes.as_mut()),
+ Some(kv_cache.v_scales.as_mut()),
Some(&rope.cosines),
Some(&rope.sines),
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ Default::default(),
self.num_heads,
- Some(self.num_heads),
- self.head_dim,
Some(rope.dim),
- Some(0),
+ 0,
3 * self.model_dim,
token_count,
+ token_count,
command_buffer,
);
Ok(PreparedPrefixAttention {
- queries,
+ query_codes,
+ query_scales,
kv_cache,
})
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
index b4f0b8274..95143ba3c 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
@@ -10,13 +10,18 @@ use crate::{
backends::{
common::{
Backend, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,
- Context, Kernels, gpu_types::weaver::MetadataIdx, kernel::AncestorAttentionKernel,
+ Context, Kernels,
+ gpu_types::weaver::MetadataIdx,
+ kernel::{AncestorAttentionKernel, AttentionPrepareKernel},
},
cpu::Cpu,
metal::Metal,
},
+ data_type::DataType,
+ encodable_block::mixer::attention::KVCache,
tests::{
assert::assert_eq_float,
+ attention::kv_layout,
helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context},
},
};
@@ -28,8 +33,8 @@ const MAX_DEPTH: u32 = 8;
struct Runner<B: Backend> {
context: Arc<B::Context>,
kernel: <B::Kernels as Kernels>::AncestorAttentionKernel,
- prefix_kv: B::GlobalGpuBuffer,
- node_kv: B::GlobalGpuBuffer,
+ prefix_kv: KVCache<B>,
+ node_kv: KVCache<B>,
current_qkv: B::GlobalGpuBuffer,
cosines: B::GlobalGpuBuffer,
sines: B::GlobalGpuBuffer,
@@ -90,12 +95,66 @@ impl<B: Backend> Runner<B> {
}
let context = create_context::<B>();
- let kernel =
- <B::Kernels as Kernels>::AncestorAttentionKernel::new(context.as_ref(), HEAD_DIM as u32, NUM_HEADS)
- .unwrap();
+ let layout = kv_layout::<B>(&context, HEAD_DIM as u32, NUM_HEADS);
+ let kernel = <B::Kernels as Kernels>::AncestorAttentionKernel::new(
+ context.as_ref(),
+ HEAD_DIM as u32,
+ NUM_HEADS,
+ layout.backend_opaque_layout,
+ )
+ .unwrap();
+ let prepare_cache = |length: usize, offset| {
+ let mut command = context.create_command_buffer(None, None).unwrap();
+ let mut kv = KVCache::<B>::allocate_scratch(layout, length as u32, &mut command).unwrap();
+ let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ &context,
+ DataType::BF16,
+ DataType::F32,
+ HEAD_DIM as u32,
+ false,
+ NUM_HEADS,
+ layout.backend_opaque_layout,
+ true,
+ false,
+ false,
+ false,
+ )
+ .unwrap();
+ let data = create_buffer_with_data::<B, bf16>(&context, &values(length * kv_width, offset));
+ command.encode_fill(kv.k_codes.as_mut(), 0);
+ command.encode_fill(kv.v_codes.as_mut(), 128);
+ command.encode_fill(kv.k_scales.as_mut(), 0);
+ command.encode_fill(kv.v_scales.as_mut(), 0);
+ let mut q = create_buffer::<B, i8>(&context, 1);
+ let mut qs = create_buffer::<B, bf16>(&context, 1);
+ prepare.encode(
+ &data,
+ &mut q,
+ &mut qs,
+ Some(kv.k_codes.as_mut()),
+ Some(kv.k_scales.as_mut()),
+ Some(kv.v_codes.as_mut()),
+ Some(kv.v_scales.as_mut()),
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ Default::default(),
+ 0,
+ None,
+ 0,
+ kv_width as u32,
+ length as u32,
+ 0,
+ &mut command,
+ );
+ block_on(command.end_encoding().submit().wait_until_completed()).unwrap();
+ kv
+ };
Self {
- prefix_kv: create_buffer_with_data::<B, bf16>(&context, &values(prefix_length * kv_width, 0)),
- node_kv: create_buffer_with_data::<B, bf16>(&context, &values(nodes * kv_width, 11)),
+ prefix_kv: prepare_cache(prefix_length, 0),
+ node_kv: prepare_cache(nodes, 11),
current_qkv: create_buffer_with_data::<B, bf16>(&context, &values(rows * qkv_width, 29)),
cosines: create_buffer_with_data::<B, f32>(&context, &cosines),
sines: create_buffer_with_data::<B, f32>(&context, &sines),
@@ -120,8 +179,14 @@ impl<B: Backend> Runner<B> {
let mut command_buffer = self.context.create_command_buffer(None, None).unwrap();
for _ in 0..repetitions {
self.kernel.encode(
- &self.prefix_kv,
- &mut self.node_kv,
+ self.prefix_kv.k_codes.as_ref(),
+ self.prefix_kv.k_scales.as_ref(),
+ self.prefix_kv.v_codes.as_ref(),
+ self.prefix_kv.v_scales.as_ref(),
+ self.node_kv.k_codes.as_mut(),
+ self.node_kv.k_scales.as_mut(),
+ self.node_kv.v_codes.as_mut(),
+ self.node_kv.v_scales.as_mut(),
&self.current_qkv,
&self.cosines,
&self.sines,
@@ -147,16 +212,13 @@ impl<B: Backend> Runner<B> {
fn ancestor_attention_matches_cpu() {
let mut cpu = Runner::<Cpu>::new(4, 5, 3, 16);
cpu.encode(1);
- let expected_output = buffer_to_vec::<Cpu, bf16>(&cpu.context, &cpu.output);
- let expected_node_kv = buffer_to_vec::<Cpu, bf16>(&cpu.context, &cpu.node_kv);
+ let expected = buffer_to_vec::<Cpu, bf16>(&cpu.context, &cpu.output);
let mut metal = Runner::<Metal>::new(4, 5, 3, 16);
metal.encode(1);
- let actual_output = buffer_to_vec::<Metal, bf16>(&metal.context, &metal.output);
- let actual_node_kv = buffer_to_vec::<Metal, bf16>(&metal.context, &metal.node_kv);
+ let actual = buffer_to_vec::<Metal, bf16>(&metal.context, &metal.output);
- assert_eq_float(&expected_output, &actual_output, 0.02, "AncestorAttention output");
- assert_eq!(actual_node_kv, expected_node_kv);
+ assert_eq_float(&expected, &actual, 0.02, "AncestorAttention output");
}
#[uzu_test]
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
index 6ef24aeac..12c1df923 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
@@ -3,200 +3,172 @@ use half::bf16;
use uzu_engine_macros::uzu_test;
use crate::{
- backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::{AttentionPrepareInt8Kernel, AttentionPrepareKernel},
- },
- cpu::Cpu,
+ backends::common::{
+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
+ gpu_types::qkv_norm::QKVNormParams, kernel::AttentionPrepareKernel,
},
data_type::DataType,
- tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},
+ tests::{
+ attention::kv_layout,
+ helpers::{buffer_to_vec, create_buffer_with_data, for_each_backend},
+ },
};
-struct Output {
- queries: Vec<bf16>,
- keys: Vec<bf16>,
- values: Vec<bf16>,
-}
-
-fn run<B: Backend>() -> Output {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::AttentionPrepareKernel::new(
- &context,
- DataType::BF16,
- DataType::F32,
- true,
- false,
- )
- .expect("Failed to create AttentionPrepareKernel");
- let qkvg = [
- 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 101.0, 102.0, 103.0, 104.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0,
- 18.0, 111.0, 112.0, 113.0, 114.0,
- ]
- .map(bf16::from_f32);
- let qkvg = create_buffer_with_data::<B, bf16>(&context, &qkvg);
- let mut queries = create_buffer::<B, bf16>(&context, 8);
- let mut keys = create_buffer::<B, bf16>(&context, 4);
- let mut values = create_buffer::<B, bf16>(&context, 4);
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
-
- kernel.encode(
- &qkvg,
- &mut queries,
- Some(&mut keys),
- Some(&mut values),
- None::<&B::GlobalGpuBuffer>,
- None::<&B::GlobalGpuBuffer>,
- 2,
- Some(1),
- 2,
- None,
- Some(0),
- 12,
- 2,
- &mut command_buffer,
- );
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
-
- Output {
- queries: buffer_to_vec(&*context, &queries),
- keys: buffer_to_vec(&*context, &keys),
- values: buffer_to_vec(&*context, &values),
- }
-}
-
-fn assert_output(
- output: Output,
- backend: &str,
-) {
- let expected_queries = [1.0, 2.0, 11.0, 12.0, 3.0, 4.0, 13.0, 14.0].map(bf16::from_f32);
- let expected_keys = [5.0, 6.0, 15.0, 16.0].map(bf16::from_f32);
- let expected_values = [7.0, 8.0, 17.0, 18.0].map(bf16::from_f32);
-
- assert_eq!(output.queries, expected_queries, "query mismatch on {backend}");
- assert_eq!(output.keys, expected_keys, "key mismatch on {backend}");
- assert_eq!(output.values, expected_values, "value mismatch on {backend}");
-}
-
-fn run_query_only<B: Backend>() -> Vec<bf16> {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::AttentionPrepareKernel::new(
- &context,
- DataType::BF16,
- DataType::F32,
- false,
- false,
- )
- .expect("Failed to create AttentionPrepareKernel");
- let qg = [1.0, 2.0, 3.0, 4.0, 101.0, 102.0, 103.0, 104.0, 11.0, 12.0, 13.0, 14.0, 111.0, 112.0, 113.0, 114.0]
- .map(bf16::from_f32);
- let qg = create_buffer_with_data::<B, bf16>(&context, &qg);
- let mut queries = create_buffer::<B, bf16>(&context, 8);
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
-
- kernel.encode(
- &qg,
- &mut queries,
- None::<&mut B::GlobalGpuBuffer>,
- None::<&mut B::GlobalGpuBuffer>,
- None::<&B::GlobalGpuBuffer>,
- None::<&B::GlobalGpuBuffer>,
- 2,
- None,
- 2,
- None,
- None,
- 8,
- 2,
- &mut command_buffer,
- );
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
-
- buffer_to_vec(&*context, &queries)
-}
-
-#[uzu_test]
-fn test_attention_prepare_uses_qkvg_row_stride() {
- assert_output(run::<Cpu>(), "CPU");
- for_each_non_cpu_backend!(|B| {
- assert_output(run::<B>(), std::any::type_name::<B>());
- });
-}
-
-#[uzu_test]
-fn test_attention_prepare_uses_query_gate_row_stride() {
- let expected = [1.0, 2.0, 11.0, 12.0, 3.0, 4.0, 13.0, 14.0].map(bf16::from_f32);
- assert_eq!(run_query_only::<Cpu>(), expected, "query mismatch on CPU");
- for_each_non_cpu_backend!(|B| {
- assert_eq!(run_query_only::<B>(), expected, "query mismatch on {}", std::any::type_name::<B>());
- });
-}
-
#[derive(Debug, PartialEq)]
-struct Int8Output {
+struct PrepareOutput {
codes: [Vec<u8>; 3],
scales: [Vec<bf16>; 3],
}
-fn run_int8<B: Backend>(num_q_heads: u32) -> Int8Output {
- const DIM: usize = 256;
+#[derive(Clone, Copy)]
+struct NormCase {
+ full_layer: bool,
+ enabled: [bool; 3],
+ affine: [bool; 3],
+}
+
+fn run_prepare<B: Backend, const DIM: usize>(
+ num_q_heads: u32,
+ normalization: NormCase,
+ fused: bool,
+ rope: bool,
+) -> PrepareOutput {
const CACHE_TOKENS: usize = 64;
+ const SUFFIX: usize = 2;
+ const ROW_PADDING: usize = 5;
let code_bytes = CACHE_TOKENS * DIM;
- let rows: Vec<bf16> = (0..3 * DIM).map(|i| bf16::from_f32((i as f32 * 0.37).sin())).collect();
+ let norm_params = QKVNormParams {
+ enabled: normalization.enabled.map(u32::from),
+ full_layer: [u32::from(normalization.full_layer); 3],
+ epsilon: [1e-6, 1e-5, 1e-4],
+ scale_offset: [0.0, 1.0, 0.25],
+ };
+ let weights: [Vec<f32>; 3] =
+ std::array::from_fn(|head| (0..DIM).map(|i| 0.5 + (i as f32 * 0.13 + head as f32).sin() * 0.3).collect());
+ let mut rows = Vec::new();
+ for token in 0..SUFFIX {
+ for head in (1 - num_q_heads) as usize..3 {
+ let mut values = (0..DIM)
+ .map(|i| bf16::from_f32(((token * 3 * DIM + head * DIM + i) as f32 * 0.37).sin()))
+ .collect::<Vec<_>>();
+ if !fused && normalization.enabled[head] {
+ let sum = values.iter().map(|v| v.to_f32() * v.to_f32()).sum::<f32>();
+ let inverse_rms = (sum / DIM as f32 + norm_params.epsilon[head]).sqrt().recip();
+ for (i, value) in values.iter_mut().enumerate() {
+ let normalized = value.to_f32() * inverse_rms;
+ let scale = weights[head][i] + norm_params.scale_offset[head];
+ *value = if !normalization.affine[head] {
+ bf16::from_f32(normalized)
+ } else if normalization.full_layer {
+ bf16::from_f32(normalized * scale)
+ } else {
+ bf16::from_f32(normalized) * bf16::from_f32(scale)
+ };
+ }
+ }
+ rows.extend(values);
+ }
+ rows.extend([bf16::ZERO; ROW_PADDING]);
+ }
let context = block_on(B::Context::new()).unwrap();
- let qkvg = create_buffer_with_data::<B, bf16>(&context, &rows[(1 - num_q_heads) as usize * DIM..]);
- let mut q_codes = create_buffer_with_data::<B, i8>(&context, &[0; DIM]);
- let mut q_scales = create_buffer_with_data::<B, bf16>(&context, &[bf16::ZERO]);
+ let layout = kv_layout::<B>(&context, DIM as u32, 1);
+ let qkvg = create_buffer_with_data::<B, bf16>(&context, &rows);
+ let norm_scales = weights.map(|weights| create_buffer_with_data::<B, f32>(&context, &weights));
+ let mut q_codes = create_buffer_with_data::<B, i8>(&context, &vec![0; SUFFIX * DIM]);
+ let mut q_scales = create_buffer_with_data::<B, bf16>(&context, &[bf16::ZERO; SUFFIX]);
let mut k_codes = create_buffer_with_data::<B, i8>(&context, &vec![0; code_bytes]);
let mut v_codes = create_buffer_with_data::<B, u8>(&context, &vec![0; code_bytes]);
let mut k_scales = create_buffer_with_data::<B, bf16>(&context, &[bf16::ZERO; CACHE_TOKENS]);
let mut v_scales = create_buffer_with_data::<B, bf16>(&context, &[bf16::ZERO; CACHE_TOKENS]);
- let kernel = <B::Kernels as Kernels>::AttentionPrepareInt8Kernel::new(
+ let rope_dim = DIM as u32 / 2;
+ let cosines = create_buffer_with_data::<B, f32>(
+ &context,
+ &(0..SUFFIX as u32 * rope_dim).map(|i| (i as f32 * 0.07).cos()).collect::<Vec<_>>(),
+ );
+ let sines = create_buffer_with_data::<B, f32>(
+ &context,
+ &(0..SUFFIX as u32 * rope_dim).map(|i| (i as f32 * 0.07).sin()).collect::<Vec<_>>(),
+ );
+ let affine = normalization.affine.map(|affine| affine && fused);
+ let kernel = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
&context,
DataType::BF16,
DataType::F32,
DIM as u32,
- false,
- true,
+ rope,
1,
+ layout.backend_opaque_layout,
true,
+ affine[0],
+ affine[1],
+ affine[2],
)
.unwrap();
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
kernel.encode(
&qkvg,
- None::<&mut B::GlobalGpuBuffer>,
- Some(&mut q_codes),
- Some(&mut q_scales),
+ &mut q_codes,
+ &mut q_scales,
Some(&mut k_codes),
Some(&mut k_scales),
Some(&mut v_codes),
Some(&mut v_scales),
- None::<&B::GlobalGpuBuffer>,
- None::<&B::GlobalGpuBuffer>,
+ rope.then_some(&cosines),
+ rope.then_some(&sines),
+ affine[0].then_some(&norm_scales[0]),
+ affine[1].then_some(&norm_scales[1]),
+ affine[2].then_some(&norm_scales[2]),
+ if fused {
+ norm_params
+ } else {
+ QKVNormParams::default()
+ },
num_q_heads,
- None,
+ rope.then_some(rope_dim),
33,
- (num_q_heads + 2) * DIM as u32,
- 1,
- num_q_heads,
+ (num_q_heads + 2) * DIM as u32 + ROW_PADDING as u32,
+ SUFFIX as u32,
+ num_q_heads * SUFFIX as u32,
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
-
- Int8Output {
+ PrepareOutput {
codes: [&q_codes, &k_codes, &v_codes].map(|buffer| buffer_to_vec::<B, u8>(&context, buffer)),
scales: [&q_scales, &k_scales, &v_scales].map(|buffer| buffer_to_vec::<B, bf16>(&context, buffer)),
}
}
#[uzu_test]
-fn test_attention_prepare_int8() {
- for num_q_heads in [0, 1] {
- let cpu = run_int8::<Cpu>(num_q_heads);
- for_each_non_cpu_backend!(|B| {
- assert_eq!(cpu, run_int8::<B>(num_q_heads), "INT8 prepare mismatch on {}", std::any::type_name::<B>());
- });
+fn test_attention_prepare_fused_norm() {
+ fn check<const DIM: usize>() {
+ for queries in [0, 1] {
+ for full_layer in [false, true] {
+ for (enabled, affine) in [
+ ([true, true, false], [true, true, false]),
+ ([true, true, true], [false, false, false]),
+ ([false, true, true], [false, false, true]),
+ ] {
+ let case = NormCase {
+ full_layer,
+ enabled,
+ affine,
+ };
+ for rope in [false, true] {
+ for_each_backend!(|B| {
+ let separate = run_prepare::<B, DIM>(queries, case, false, rope);
+ let fused = run_prepare::<B, DIM>(queries, case, true, rope);
+ assert_eq!(
+ separate, fused,
+ "fused norm mismatch D{DIM} queries={queries} full_layer={full_layer} rope={rope}"
+ );
+ });
+ }
+ }
+ }
+ }
}
+ check::<64>();
+ check::<128>();
+ check::<256>();
+ check::<512>();
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
index afe029377..6ec5b1e6f 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
@@ -1,286 +1,117 @@
-use std::fmt::{Debug, Display};
-
-use futures::executor::block_on;
use half::bf16;
-use num_traits::Float;
use uzu_engine_macros::uzu_test;
use crate::{
- backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- gpu_types::kv_cache_update::Copy,
- kernel::{KVCacheUpdateInt8Kernel, KVCacheUpdateKernel, kv_layout::Int8KVLayout},
- },
- cpu::Cpu,
+ backends::common::{
+ Backend, Context, Kernels,
+ gpu_types::kv_cache_update::Copy,
+ kernel::{AttentionPrepareKernel, KVCacheUpdateKernel, kv_layout::KVLayout},
},
- data_type::DataTypeRepr,
+ data_type::DataType,
+ encodable_block::mixer::attention::KVCache,
tests::{
- assert::assert_eq_float,
- helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},
+ attention::kv_layout,
+ helpers::{
+ buffer_readback, buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_backend,
+ submit_command_buffer,
+ },
},
};
-struct Input<T: DataTypeRepr + Float> {
- keys: Box<[T]>,
- values: Box<[T]>,
- copies: Vec<Copy>,
- element_dim: u32,
-}
-
-fn make_data<T: DataTypeRepr + Float>(
- max_sequence_length: usize,
- element_dim: usize,
-) -> (Vec<T>, Vec<T>) {
- let total = max_sequence_length * element_dim;
- let mut keys = Vec::with_capacity(total);
- let mut values = Vec::with_capacity(total);
- for i in 0..total {
- keys.push(T::from(1.0 + i as f32 * 0.1).unwrap());
- values.push(T::from(100.0 + i as f32 * 0.1).unwrap());
- }
- (keys, values)
-}
-
-fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> (Vec<T>, Vec<T>) {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::KVCacheUpdateKernel::new(&context, T::data_type())
- .expect("Failed to create KVCacheUpdateKernel");
-
- let mut keys = create_buffer_with_data::<B, T>(&context, &input.keys);
- let mut values = create_buffer_with_data::<B, T>(&context, &input.values);
-
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");
- kernel.encode(
- &mut keys,
- &mut values,
- &input.copies,
- input.copies.len() as u32,
- input.element_dim,
- &mut command_buffer,
+const HEAD_DIM: u32 = 256;
+const NUM_HEADS: u32 = 2;
+const KEYS: u32 = 64;
+const ROW_WIDTH: usize = (2 * NUM_HEADS * HEAD_DIM) as usize;
+
+fn prepare_cache<B: Backend>(
+ context: &B::Context,
+ layout: KVLayout,
+ rows: &[bf16],
+) -> KVCache<B> {
+ let mut command = context.create_command_buffer(None, None).unwrap();
+ let mut kv = KVCache::<B>::allocate_scratch(layout, KEYS, &mut command).unwrap();
+ let input = create_buffer_with_data::<B, bf16>(context, rows);
+ let mut q = create_buffer::<B, i8>(context, 1);
+ let mut qs = create_buffer::<B, bf16>(context, 1);
+ let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ context,
+ DataType::BF16,
+ DataType::F32,
+ HEAD_DIM,
+ false,
+ NUM_HEADS,
+ layout.backend_opaque_layout,
+ true,
+ false,
+ false,
+ false,
+ )
+ .unwrap();
+ prepare.encode(
+ &input,
+ &mut q,
+ &mut qs,
+ Some(kv.k_codes.as_mut()),
+ Some(kv.k_scales.as_mut()),
+ Some(kv.v_codes.as_mut()),
+ Some(kv.v_scales.as_mut()),
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ Default::default(),
+ 0,
+ None,
+ 0,
+ ROW_WIDTH as u32,
+ KEYS,
+ 0,
+ &mut command,
);
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
-
- (buffer_to_vec(&*context, &keys), buffer_to_vec(&*context, &values))
-}
-
-/// Single copy between two different positions.
-fn get_test_data_single_copy<T: DataTypeRepr + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
- let num_heads = 2usize;
- let max_sequence_length = 4usize;
- let head_dim = 3usize;
- let element_dim = num_heads * head_dim;
-
- let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
-
- let copies = vec![Copy {
- source: 0,
- destination: 2,
- }];
-
- let input = Input {
- keys: keys.into_boxed_slice(),
- values: values.into_boxed_slice(),
- copies: copies.clone(),
- element_dim: element_dim as u32,
- };
-
- let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
- (input, expected_keys, expected_values)
-}
-
-/// Multiple copies.
-fn get_test_data_multi_copy<T: DataTypeRepr + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
- let num_heads = 2usize;
- let max_sequence_length = 8usize;
- let head_dim = 4usize;
- let element_dim = num_heads * head_dim;
-
- let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
-
- let copies = vec![
- Copy {
- source: 1,
- destination: 3,
- },
- Copy {
- source: 0,
+ submit_command_buffer(command);
+ kv
+}
+
+fn check_kv_copy<B: Backend>() {
+ let context = create_context::<B>();
+ let layout = kv_layout::<B>(&context, HEAD_DIM, NUM_HEADS);
+ let mut rows: Vec<bf16> =
+ (0..KEYS as usize * ROW_WIDTH).map(|i| bf16::from_f32(((i * 37 % 251) as f32 - 125.0) / 128.0)).collect();
+ let mut actual = prepare_cache::<B>(&context, layout, &rows);
+ rows.copy_within(40 * ROW_WIDTH..41 * ROW_WIDTH, 5 * ROW_WIDTH);
+ let expected = prepare_cache::<B>(&context, layout, &rows);
+ let kernel =
+ <B::Kernels as Kernels>::KVCacheUpdateKernel::new(&context, HEAD_DIM, NUM_HEADS, layout.backend_opaque_layout)
+ .unwrap();
+ let mut command = context.create_command_buffer(None, None).unwrap();
+ kernel.encode(
+ actual.k_codes.as_mut(),
+ actual.v_codes.as_mut(),
+ actual.k_scales.as_mut(),
+ actual.v_scales.as_mut(),
+ &[Copy {
+ source: 40,
destination: 5,
- },
- Copy {
- source: 3,
- destination: 6,
- },
- ];
-
- let input = Input {
- keys: keys.into_boxed_slice(),
- values: values.into_boxed_slice(),
- copies: copies.clone(),
- element_dim: element_dim as u32,
- };
-
- let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
- (input, expected_keys, expected_values)
-}
-
-/// No copies — data should remain unchanged.
-fn get_test_data_no_copy<T: DataTypeRepr + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
- let num_heads = 2usize;
- let max_sequence_length = 4usize;
- let head_dim = 3usize;
- let element_dim = num_heads * head_dim;
-
- let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
-
- let expected_keys = keys.clone();
- let expected_values = values.clone();
-
- let input = Input {
- keys: keys.into_boxed_slice(),
- values: values.into_boxed_slice(),
- copies: vec![],
- element_dim: element_dim as u32,
- };
-
- (input, expected_keys, expected_values)
-}
-
-/// Larger dimensions to exercise more threads.
-fn get_test_data_large<T: DataTypeRepr + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
- let num_heads = 8usize;
- let max_sequence_length = 64usize;
- let head_dim = 128usize;
- let element_dim = num_heads * head_dim;
-
- let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
-
- let copies = vec![
- Copy {
- source: 0,
- destination: 63,
- },
- Copy {
- source: 10,
- destination: 30,
- },
- Copy {
- source: 5,
- destination: 20,
- },
- ];
-
- let input = Input {
- keys: keys.into_boxed_slice(),
- values: values.into_boxed_slice(),
- copies: copies.clone(),
- element_dim: element_dim as u32,
- };
-
- let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
- (input, expected_keys, expected_values)
-}
-
-fn test_internal<T: DataTypeRepr + Float + Debug + Display>(
- input: &Input<T>,
- expected_keys: &[T],
- expected_values: &[T],
- test_name: &str,
-) {
- let eps = 1e-5;
- for_each_non_cpu_backend!(|B| {
- let (actual_keys, actual_values) = get_output::<T, B>(input);
- let msg = format!("KVCacheUpdate {} keys failed with backend={}", test_name, std::any::type_name::<B>(),);
- assert_eq_float::<T>(expected_keys, &actual_keys, eps, &msg);
- let msg = format!("KVCacheUpdate {} values failed with backend={}", test_name, std::any::type_name::<B>(),);
- assert_eq_float::<T>(expected_values, &actual_values, eps, &msg);
- });
-}
-
-fn test_single_copy_internal<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_single_copy::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "single_copy");
-}
-
-fn test_multi_copy_internal<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_multi_copy::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "multi_copy");
-}
-
-fn test_no_copy_internal<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_no_copy::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "no_copy");
-}
-
-fn test_large_internal<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_large::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "large");
-}
-
-// Single copy tests
-#[uzu_test]
-fn test_single_copy_bf16() {
- test_single_copy_internal::<bf16>();
-}
-
-// Multi copy tests
-#[uzu_test]
-fn test_multi_copy_bf16() {
- test_multi_copy_internal::<bf16>();
-}
-
-// No copy tests
-#[uzu_test]
-fn test_no_copy_bf16() {
- test_no_copy_internal::<bf16>();
-}
-
-// Large dimension tests
-#[uzu_test]
-fn test_large_bf16() {
- test_large_internal::<bf16>();
+ }],
+ 1,
+ &mut command,
+ );
+ submit_command_buffer(command);
+ for (actual, expected) in [
+ (actual.k_codes.as_ref(), expected.k_codes.as_ref()),
+ (actual.v_codes.as_ref(), expected.v_codes.as_ref()),
+ (actual.k_scales.as_ref(), expected.k_scales.as_ref()),
+ (actual.v_scales.as_ref(), expected.v_scales.as_ref()),
+ ] {
+ assert_eq!(
+ buffer_to_vec::<B, u8>(&context, &buffer_readback::<B>(&context, actual)),
+ buffer_to_vec::<B, u8>(&context, &buffer_readback::<B>(&context, expected)),
+ );
+ }
}
#[uzu_test]
-fn test_int8_copy() {
- let expected = get_int8_output::<Cpu>();
- for_each_non_cpu_backend!(|B| {
- assert_eq!(expected, get_int8_output::<B>(), "INT8 cache update mismatch on {}", std::any::type_name::<B>());
- });
-}
-
-fn get_int8_output<B: Backend>() -> ([Vec<u8>; 2], [Vec<bf16>; 2]) {
- let layout = Int8KVLayout::new(256, 2);
- let scale_count = 64 * layout.num_kv_heads as usize;
- let code_bytes = scale_count * layout.head_dim as usize;
- let k_codes: Vec<i8> = (0..code_bytes).map(|i| ((i * 37) ^ (i >> 8)) as i8).collect();
- let v_codes: Vec<u8> = (0..code_bytes).map(|i| ((i * 19) ^ (i >> 7)) as u8).collect();
- let k_scales: Vec<bf16> = (0..scale_count).map(|i| bf16::from_f32(i as f32 + 1.0)).collect();
- let v_scales: Vec<bf16> = (0..scale_count).map(|i| bf16::from_f32(i as f32 + 129.0)).collect();
- let copies = [Copy {
- source: 40,
- destination: 5,
- }];
- let context = block_on(B::Context::new()).unwrap();
- let mut keys = create_buffer_with_data::<B, i8>(&context, &k_codes);
- let mut values = create_buffer_with_data::<B, u8>(&context, &v_codes);
- let mut key_scales = create_buffer_with_data::<B, bf16>(&context, &k_scales);
- let mut value_scales = create_buffer_with_data::<B, bf16>(&context, &v_scales);
- let kernel =
- <B::Kernels as Kernels>::KVCacheUpdateInt8Kernel::new(&context, layout.head_dim, layout.num_kv_heads).unwrap();
- let mut command_buffer = context.create_command_buffer(None, None).unwrap();
- kernel.encode(
- &mut keys,
- &mut values,
- &mut key_scales,
- &mut value_scales,
- &copies,
- copies.len() as u32,
- &mut command_buffer,
- );
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (
- [&keys, &values].map(|buffer| buffer_to_vec::<B, u8>(&context, buffer)),
- [&key_scales, &value_scales].map(|buffer| buffer_to_vec::<B, bf16>(&context, buffer)),
- )
+fn test_kv_copy() {
+ for_each_backend!(|B| check_kv_copy::<B>());
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs
index f23375caf..59dd2f91a 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs
@@ -1,5 +1,3 @@
mod ancestor_attention_test;
mod attention_prepare_test;
mod kv_cache_update_test;
-mod qkv_norm_test;
-mod sigmoid_gate_test;
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs
deleted file mode 100644
index d8c6c758d..000000000
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs
+++ /dev/null
@@ -1,406 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use futures::executor::block_on;
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::uzu_test;
-
-use crate::{
- backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::QKVNormKernel,
- },
- cpu::Cpu,
- },
- data_type::{DataType, DataTypeRepr},
- tests::{
- assert::assert_eq_float,
- helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},
- },
-};
-
-struct Input<InputT: DataTypeRepr + Float, ScaleT: DataTypeRepr + Float, OutputT: DataTypeRepr + Float> {
- qkvg: Box<[OutputT]>,
- scales: Box<[ScaleT]>,
- batch_size: u32,
- num_q_heads: u32,
- num_kv_heads: u32,
- input_row_stride: u32,
- head_dim: u32,
- epsilon: f32,
- scale_offset: f32,
- head_offset: u32,
- head_count: u32,
- full_layer: bool,
- in_place: bool,
- has_scales: bool,
- _phantom: std::marker::PhantomData<InputT>,
-}
-
-fn get_test_data<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float,
- AccumT: DataTypeRepr + Float,
->(
- head_offset: u32,
- head_count: u32,
- full_layer: bool,
- has_scales: bool,
-) -> (Input<InputT, ScaleT, OutputT>, Vec<OutputT>) {
- let batch_size = 1u32;
- let num_q_heads = 4u32;
- let num_kv_heads = 2u32;
- let head_dim = 8u32;
- let epsilon = 1e-6f32;
- let scale_offset = 0.0f32;
-
- // QKV layout: [Q0, Q1, Q2, Q3, K0, K1, V0, V1] where each head has head_dim elements
- let qkv_width = ((num_q_heads + 2 * num_kv_heads) * head_dim) as usize;
- let total_size = (batch_size as usize) * qkv_width;
-
- let mut qkv_data_f32 = vec![0.0f32; total_size];
-
- // Q heads: values 1.0, 1.1, 1.2, 1.3, ...
- for head in 0..num_q_heads {
- for dim in 0..head_dim {
- let idx = (head * head_dim + dim) as usize;
- qkv_data_f32[idx] = 1.0 + (head as f32) * 0.1 + (dim as f32) * 0.01;
- }
- }
-
- // K heads: values 2.0, 2.1, 2.2, 2.3, ... (start after Q heads)
- let k_offset = (num_q_heads * head_dim) as usize;
- for head in 0..num_kv_heads {
- for dim in 0..head_dim {
- let idx = k_offset + (head * head_dim + dim) as usize;
- qkv_data_f32[idx] = 2.0 + (head as f32) * 0.1 + (dim as f32) * 0.01;
- }
- }
-
- // V heads: values 3.0, 3.1, 3.2, 3.3, ... (start after K heads)
- let v_offset = ((num_q_heads + num_kv_heads) * head_dim) as usize;
- for head in 0..num_kv_heads {
- for dim in 0..head_dim {
- let idx = v_offset + (head * head_dim + dim) as usize;
- qkv_data_f32[idx] = 3.0 + (head as f32) * 0.1 + (dim as f32) * 0.01;
- }
- }
-
- // Scale data (identity scaling)
- let scale_data: Vec<ScaleT> = (0..head_dim).map(|_| ScaleT::one()).collect();
- let qkv_data: Vec<OutputT> = qkv_data_f32.iter().map(|&x| OutputT::from(x).unwrap()).collect();
-
- let input = Input {
- qkvg: qkv_data.into_boxed_slice(),
- scales: scale_data.into_boxed_slice(),
- batch_size,
- num_q_heads,
- num_kv_heads,
- input_row_stride: qkv_width as u32,
- head_dim,
- epsilon,
- scale_offset,
- head_offset,
- head_count,
- full_layer,
- in_place: true,
- has_scales,
- _phantom: std::marker::PhantomData,
- };
-
- let expected = get_output::<Cpu, InputT, ScaleT, OutputT, AccumT>(&input);
- (input, expected)
-}
-
-fn get_output<
- B: Backend,
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float,
- AccumT: DataTypeRepr + Float,
->(
- input: &Input<InputT, ScaleT, OutputT>
-) -> Vec<OutputT> {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::QKVNormKernel::new(
- &context,
- InputT::data_type(),
- ScaleT::data_type(),
- OutputT::data_type(),
- AccumT::data_type(),
- input.in_place,
- input.has_scales,
- )
- .expect("Failed to create QKVNormKernel");
-
- let mut qkvg = create_buffer_with_data::<B, OutputT>(&context, &input.qkvg);
- let scales = input.has_scales.then(|| create_buffer_with_data::<B, ScaleT>(&context, &input.scales));
-
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
- kernel.encode(
- None::<&B::GlobalGpuBuffer>,
- scales.as_ref(),
- &mut qkvg,
- input.batch_size,
- input.input_row_stride,
- input.head_dim,
- input.epsilon,
- input.scale_offset,
- input.head_offset,
- input.head_count,
- input.full_layer,
- &mut command_buffer,
- );
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
-
- buffer_to_vec(&*context, &qkvg)
-}
-
-fn test_internal<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->(
- input: &Input<InputT, ScaleT, OutputT>,
- expected: &[OutputT],
-) {
- let eps = if [InputT::data_type(), ScaleT::data_type(), OutputT::data_type(), AccumT::data_type()]
- .into_iter()
- .any(|data_type| data_type == DataType::BF16)
- {
- 1e-2
- } else {
- 1e-5
- };
-
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, InputT, ScaleT, OutputT, AccumT>(input);
- let msg = format!(
- "QKVNorm kernel test failed with backend={}, head_offset={}, head_count={}, full_layer={}, has_scales={}",
- std::any::type_name::<B>(),
- input.head_offset,
- input.head_count,
- input.full_layer,
- input.has_scales,
- );
- assert_eq_float::<OutputT>(expected, &output, eps, &msg);
- });
-}
-
-fn test_q_norm<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->() {
- for full_layer in [true, false] {
- // Normalize Q heads: head_offset=0, head_count=num_q_heads(4)
- let (input, expected) = get_test_data::<InputT, ScaleT, OutputT, AccumT>(0, 4, full_layer, true);
- test_internal::<InputT, ScaleT, OutputT, AccumT>(&input, &expected);
- }
-}
-
-fn test_k_norm<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->() {
- for full_layer in [true, false] {
- // Normalize K heads: head_offset=num_q_heads(4), head_count=num_kv_heads(2)
- let (input, expected) = get_test_data::<InputT, ScaleT, OutputT, AccumT>(4, 2, full_layer, true);
- test_internal::<InputT, ScaleT, OutputT, AccumT>(&input, &expected);
- }
-}
-
-fn test_v_norm_no_scales<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->() {
- let (input, expected) = get_test_data::<InputT, ScaleT, OutputT, AccumT>(6, 2, true, false);
- test_internal::<InputT, ScaleT, OutputT, AccumT>(&input, &expected);
-}
-
-fn test_addressing<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->() {
- // Test that Q norm only modifies Q heads and leaves K/V untouched
- let (input, _expected) = get_test_data::<InputT, ScaleT, OutputT, AccumT>(0, 4, false, true);
-
- let num_q_heads = input.num_q_heads as usize;
- let head_dim = input.head_dim as usize;
- let k_start = num_q_heads * head_dim;
- let qkv_len = input.qkvg.len();
-
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, InputT, ScaleT, OutputT, AccumT>(&input);
-
- // Q heads should be modified (different from input)
- for i in 0..(num_q_heads * head_dim) {
- let orig = input.qkvg[i].to_f32().unwrap();
- let out = output[i].to_f32().unwrap();
- assert!(
- (out - orig).abs() > 0.001,
- "Q head element {} was not modified by Q norm on backend {}",
- i,
- std::any::type_name::<B>(),
- );
- }
-
- // K and V heads should be unchanged
- for i in k_start..qkv_len {
- let orig = input.qkvg[i].to_f32().unwrap();
- let out = output[i].to_f32().unwrap();
- assert!(
- (out - orig).abs() < 1e-6,
- "K/V element {} was incorrectly modified by Q norm on backend {}: expected {}, got {}",
- i,
- std::any::type_name::<B>(),
- orig,
- out,
- );
- }
- });
-}
-
-fn test_v_addressing<
- InputT: DataTypeRepr + Float,
- ScaleT: DataTypeRepr + Float,
- OutputT: DataTypeRepr + Float + Debug + Display,
- AccumT: DataTypeRepr + Float,
->() {
- // Weightless V norm must modify only V heads and leave Q/K untouched.
- let (input, _expected) = get_test_data::<InputT, ScaleT, OutputT, AccumT>(6, 2, true, false);
-
- let num_q_heads = input.num_q_heads as usize;
- let num_kv_heads = input.num_kv_heads as usize;
- let head_dim = input.head_dim as usize;
- let v_start = (num_q_heads + num_kv_heads) * head_dim;
- let qkv_len = input.qkvg.len();
-
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, InputT, ScaleT, OutputT, AccumT>(&input);
-
- for i in 0..v_start {
- let orig = input.qkvg[i].to_f32().unwrap();
- let out = output[i].to_f32().unwrap();
- assert!(
- (out - orig).abs() < 1e-6,
- "Q/K element {} was incorrectly modified by V norm on backend {}: expected {}, got {}",
- i,
- std::any::type_name::<B>(),
- orig,
- out,
- );
- }
-
- for i in v_start..qkv_len {
- let orig = input.qkvg[i].to_f32().unwrap();
- let out = output[i].to_f32().unwrap();
- assert!(
- (out - orig).abs() > 0.001,
- "V head element {} was not modified by V norm on backend {}",
- i,
- std::any::type_name::<B>(),
- );
- }
- });
-}
-
-#[uzu_test]
-fn test_gated_row_stride() {
- let (input, _) = get_test_data::<f32, f32, f32, f32>(0, 4, false, false);
- let qkv_row = input.qkvg.to_vec();
- let gate_len = (input.num_q_heads * input.head_dim) as usize;
- let qkv_len = qkv_row.len();
- let input_row_stride = qkv_len + gate_len;
- let qkvg = (0..2)
- .flat_map(|batch| {
- qkv_row.iter().copied().chain((0..gate_len).map(move |index| 10.0 + batch as f32 + index as f32 * 0.01))
- })
- .collect::<Vec<_>>()
- .into_boxed_slice();
- let input = Input {
- qkvg,
- batch_size: 2,
- input_row_stride: input_row_stride as u32,
- ..input
- };
-
- let assert_addressing = |output: &[f32], backend: &str| {
- for batch in 0..input.batch_size as usize {
- let row_offset = batch * input_row_stride;
- for index in row_offset..row_offset + (input.num_q_heads * input.head_dim) as usize {
- assert_ne!(output[index], input.qkvg[index], "Q was not normalized on {backend}");
- }
- for index in row_offset + qkv_len..row_offset + input_row_stride {
- assert_eq!(output[index], input.qkvg[index], "gate was modified on {backend}");
- }
- }
- };
-
- let expected = get_output::<Cpu, f32, f32, f32, f32>(&input);
- assert_addressing(&expected, "CPU");
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, f32, f32, f32, f32>(&input);
- assert_addressing(&output, std::any::type_name::<B>());
- assert_eq_float(&expected, &output, 1e-5, "QKVG row stride mismatch");
- });
-}
-
-// Q norm tests
-#[uzu_test]
-fn test_q_norm_f32_f32_f32_f32() {
- test_q_norm::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_q_norm_bf16_bf16_bf16_f32() {
- test_q_norm::<bf16, bf16, bf16, f32>();
-}
-
-// K norm tests
-#[uzu_test]
-fn test_k_norm_f32_f32_f32_f32() {
- test_k_norm::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_k_norm_bf16_bf16_bf16_f32() {
- test_k_norm::<bf16, bf16, bf16, f32>();
-}
-
-#[uzu_test]
-fn test_v_norm_no_scales_f32_f32_f32_f32() {
- test_v_norm_no_scales::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_v_norm_no_scales_bf16_bf16_bf16_f32() {
- test_v_norm_no_scales::<bf16, bf16, bf16, f32>();
-}
-
-// Addressing tests (Q norm should not touch K/V)
-#[uzu_test]
-fn test_addressing_f32_f32_f32_f32() {
- test_addressing::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_v_addressing_f32_f32_f32_f32() {
- test_v_addressing::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_v_addressing_bf16_bf16_bf16_f32() {
- test_v_addressing::<bf16, bf16, bf16, f32>();
-}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
deleted file mode 100644
index 96c22a054..000000000
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-use std::fmt::Debug;
-
-use futures::executor::block_on;
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::uzu_test;
-
-use crate::{
- backends::{
- common::{
- Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::SigmoidGateKernel,
- },
- cpu::Cpu,
- },
- data_type::DataTypeRepr,
- tests::helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},
-};
-
-struct Config {
- num_heads: u32,
- num_kv_heads: u32,
- head_dim: u32,
- suffix_length: u32,
-}
-
-fn get_output<T: DataTypeRepr + Float, B: Backend>(
- qkvg_data: &[T],
- output_data: &[T],
- config: &Config,
-) -> Vec<T> {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::SigmoidGateKernel::new(&context, T::data_type())
- .expect("Failed to create SigmoidGateKernel");
-
- let qkvg = create_buffer_with_data::<B, T>(&context, qkvg_data);
- let mut output = create_buffer_with_data::<B, T>(&context, output_data);
-
- let mut command_buffer =
- context.as_ref().create_command_buffer(None, None).expect("Failed to create command buffer");
- let gate_dim = config.num_heads * config.head_dim;
- let gate_offset = (config.num_heads + 2 * config.num_kv_heads) * config.head_dim;
- let qkvg_dim = gate_offset + gate_dim;
- kernel.encode(
- qkvg.subrange(gate_offset as usize * size_of::<T>()..),
- &mut output,
- gate_dim,
- config.suffix_length,
- qkvg_dim,
- &mut command_buffer,
- );
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
-
- buffer_to_vec(&*context, &output)
-}
-
-fn run_test<T: DataTypeRepr + Float + Debug>(config: &Config) {
- let size = (config.suffix_length * config.num_heads * config.head_dim) as usize;
- let gate_dim = (config.num_heads * config.head_dim) as usize;
- let gate_offset = ((config.num_heads + 2 * config.num_kv_heads) * config.head_dim) as usize;
- let qkvg_dim = gate_offset + gate_dim;
-
- let qkvg_f32 = (0..config.suffix_length as usize)
- .flat_map(|row| {
- (0..qkvg_dim).map(move |column| {
- if column < gate_offset {
- return -100.0;
- }
- let gate_index = row * gate_dim + column - gate_offset;
- (gate_index as f32) * 0.1 - 2.0
- })
- })
- .collect::<Vec<_>>();
- let output_f32: Vec<f32> = (0..size).map(|i| (i as f32) * 0.05 + 0.5).collect();
-
- let qkvg_data: Vec<T> = qkvg_f32.iter().map(|&v| T::from(v).unwrap()).collect();
- let output_data: Vec<T> = output_f32.iter().map(|&v| T::from(v).unwrap()).collect();
- let expected = (0..size)
- .map(|output_index| {
- let batch_index = output_index / gate_dim;
- let gate_index = output_index % gate_dim;
- let gate = qkvg_data[batch_index * qkvg_dim + gate_offset + gate_index].to_f32().unwrap();
- let sigmoid = 1.0 / (1.0 + (-gate).exp());
- T::from(output_data[output_index].to_f32().unwrap() * sigmoid).unwrap()
- })
- .collect::<Vec<_>>();
-
- let rtol = 0.01;
-
- let assert_output = |result: &[T], backend: &str| {
- for (i, (got, exp)) in result.iter().zip(expected.iter()).enumerate() {
- let got_f32 = got.to_f32().unwrap();
- let exp_f32 = exp.to_f32().unwrap();
- let diff = (got_f32 - exp_f32).abs();
- let tol = rtol * exp_f32.abs().max(1.0);
- assert!(
- diff < tol,
- "Backend {}: mismatch at index {}: got {} expected {} (diff {}, tol {})",
- backend,
- i,
- got_f32,
- exp_f32,
- diff,
- tol,
- );
- }
- };
-
- let result = get_output::<T, Cpu>(&qkvg_data, &output_data, config);
- assert_output(&result, std::any::type_name::<Cpu>());
- for_each_non_cpu_backend!(|B| {
- let result = get_output::<T, B>(&qkvg_data, &output_data, config);
- assert_output(&result, std::any::type_name::<B>());
- });
-}
-
-#[uzu_test]
-fn test_sigmoid_gate_bf16() {
- run_test::<bf16>(&Config {
- num_heads: 8,
- num_kv_heads: 2,
- head_dim: 64,
- suffix_length: 4,
- });
- run_test::<bf16>(&Config {
- num_heads: 16,
- num_kv_heads: 4,
- head_dim: 256,
- suffix_length: 1,
- });
- run_test::<bf16>(&Config {
- num_heads: 2,
- num_kv_heads: 1,
- head_dim: 64,
- suffix_length: 8,
- });
-}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/cpu_comparison_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/cpu_comparison_test.rs
new file mode 100644
index 000000000..f0113f21c
--- /dev/null
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/cpu_comparison_test.rs
@@ -0,0 +1,296 @@
+use half::bf16;
+use uzu_engine_macros::uzu_test;
+
+use crate::{
+ backends::{
+ common::{
+ Backend, BufferRef, CommandBufferEncoding, Context, Kernels,
+ gpu_types::trie::TrieNode,
+ kernel::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, AttentionPrepareKernel,
+ },
+ },
+ cpu::Cpu,
+ metal::{Metal, gpu_types::kv_layout::KVLayout, kernel::attention::tests::default_attention_config},
+ },
+ data_type::{DataType, DataTypeRepr},
+ encodable_block::mixer::attention::{KVCache, KVCacheView},
+ tests::{
+ assert::assert_eq_float,
+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, submit_command_buffer},
+ },
+};
+
+fn run<B: Backend, T: DataTypeRepr>(
+ config: AttentionKernelConfig,
+ cache: KVCacheView,
+ nodes: &[TrieNode],
+ is_trie: bool,
+) -> (Vec<T>, f32) {
+ let context = create_context::<B>();
+ let suffix = nodes.len() as u32;
+ let prefix = cache.prefix_len();
+ let dim = config.head_dim;
+ let stride = (config.num_q_heads + 2 * config.num_groups) * dim;
+ let values: Vec<T> =
+ (0..(prefix + suffix) * stride).map(|i| T::from(((i * 17 % 251) as f32 - 125.0) / 128.0).unwrap()).collect();
+ let data = create_buffer_with_data::<B, T>(&context, &values);
+ let kernel = <B::Kernels as Kernels>::AttentionKernel::new(&context, config).unwrap();
+ let mut command = context.create_command_buffer(None, None).unwrap();
+ let mut kv = KVCache::<B>::allocate_scratch(kernel.kv_layout(), prefix + suffix, &mut command).unwrap();
+ let mut q = create_buffer::<B, i8>(&context, (config.num_q_heads * suffix * dim) as usize);
+ let mut qs = create_buffer::<B, bf16>(&context, (config.num_q_heads * suffix) as usize);
+ let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ &context,
+ config.data_type,
+ DataType::F32,
+ dim,
+ false,
+ config.num_groups,
+ kernel.kv_layout().backend_opaque_layout,
+ true,
+ false,
+ false,
+ false,
+ )
+ .unwrap();
+ command.encode_fill(kv.k_codes.as_mut(), 0x7f);
+ command.encode_fill(kv.v_codes.as_mut(), 0xff);
+ command.encode_fill(kv.k_scales.as_mut(), 0xff);
+ command.encode_fill(kv.v_scales.as_mut(), 0xff);
+ for (start, length, heads) in [(0, prefix, 0), (prefix, suffix, config.num_q_heads)] {
+ if length == 0 {
+ continue;
+ }
+ let offset = (start * stride
+ + if heads == 0 {
+ config.num_q_heads * dim
+ } else {
+ 0
+ }) as usize
+ * config.data_type.size_in_bytes();
+ prepare.encode(
+ data.subrange(offset..),
+ &mut q,
+ &mut qs,
+ Some(kv.k_codes.as_mut()),
+ Some(kv.k_scales.as_mut()),
+ Some(kv.v_codes.as_mut()),
+ Some(kv.v_scales.as_mut()),
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ Default::default(),
+ heads,
+ None,
+ start,
+ stride,
+ length,
+ heads / config.num_groups * length,
+ &mut command,
+ );
+ }
+ let trie = create_buffer_with_data::<B, u32>(&context, bytemuck::cast_slice(nodes));
+ let sinks = config
+ .has_sinks
+ .then(|| create_buffer_with_data::<B, T>(&context, &vec![T::from(1.5).unwrap(); config.num_q_heads as usize]));
+ let gate = config.gate_row_stride.map(|stride| {
+ create_buffer_with_data::<B, T>(
+ &context,
+ &(0..suffix * stride).map(|i| T::from((i % 37) as f32 / 17.0 - 1.0).unwrap()).collect::<Vec<_>>(),
+ )
+ });
+ let result = kernel
+ .encode(
+ AttentionInput {
+ query_codes: &q,
+ query_scales: &qs,
+ k_codes: kv.k_codes.as_ref(),
+ k_scales: kv.k_scales.as_ref(),
+ v_codes: kv.v_codes.as_ref(),
+ v_scales: kv.v_scales.as_ref(),
+ },
+ AttentionArguments {
+ suffix_length: suffix,
+ trie: is_trie.then_some(&trie),
+ sinks: sinks.as_ref(),
+ cache,
+ gate: gate.as_ref(),
+ },
+ &mut command,
+ )
+ .unwrap();
+ let mut output = create_buffer::<B, T>(&context, (suffix * config.num_q_heads * dim) as usize);
+ command.encode_copy(&result, &mut output);
+ submit_command_buffer(command);
+ // MXU also quantizes attention probabilities to u8.
+ let tolerance = if kernel.kv_layout().backend_opaque_layout == KVLayout::MxuTiled as u32 {
+ 1.5e-2
+ } else {
+ 5e-3
+ };
+ (buffer_to_vec::<B, T>(&context, &output), tolerance)
+}
+
+#[uzu_test]
+fn attention_windows_sinks_and_head_dims() {
+ let nodes: &[TrieNode] = bytemuck::cast_slice::<[u32; 3], TrieNode>(&[
+ [0, 7, 0],
+ [1, 3, 1],
+ [2, 2, 2],
+ [3, 3, 2],
+ [4, 7, 1],
+ [5, 6, 2],
+ [6, 6, 3],
+ [7, 7, 2],
+ ]);
+ for dim in [64, 128, 256, 512] {
+ for (causal, ring, window, prefix, scale) in [
+ (true, false, None, 37, None),
+ (true, true, None, 37, None),
+ (false, true, None, 37, None),
+ (false, false, None, 37, None),
+ (false, false, Some(1), 37, None),
+ (false, false, Some(7), 37, None),
+ (false, true, Some(129), 37, None),
+ (true, true, Some(0), 37, None),
+ (true, false, Some(0), 37, None),
+ (true, false, None, 37, Some(0.0)),
+ (true, false, None, 37, Some(-0.125)),
+ (true, false, Some(1), 17, None),
+ (false, true, Some(17), 17, None),
+ (true, true, Some(7), 17, None),
+ (false, false, None, 0, None),
+ (true, false, Some(1), 37, None),
+ (false, true, Some(17), 37, None),
+ (true, true, Some(7), 37, None),
+ ] {
+ let mut config = default_attention_config::<bf16>(dim, 8, 2, causal);
+ config.has_sinks = window != Some(0);
+ config.gate_row_stride = Some(8 * dim as u32 + 7);
+ config.is_kv_cache_ring = ring;
+ config.sliding_window_size = window;
+ config.scale = scale;
+ let cache = if ring {
+ KVCacheView::ring(prefix, 11)
+ } else {
+ KVCacheView::full(prefix)
+ };
+ for is_trie in [false, true] {
+ let (expected, _) = run::<Cpu, bf16>(config, cache, nodes, is_trie);
+ let (actual, tolerance) = run::<Metal, bf16>(config, cache, nodes, is_trie);
+ assert_eq_float(
+ &expected,
+ &actual,
+ tolerance,
+ &format!(
+ "INT8 D{dim} causal={causal} ring={ring} window={window:?} scale={scale:?} trie={is_trie}"
+ ),
+ );
+ }
+ }
+ }
+}
+
+#[uzu_test]
+fn attention_large_tree_and_f32() {
+ let words: Vec<[u32; 3]> = (0..80)
+ .map(|i| {
+ if i == 0 {
+ [0, 79, 0]
+ } else {
+ [i, i, 1]
+ }
+ })
+ .collect();
+ let nodes: &[TrieNode] = bytemuck::cast_slice(&words);
+ let config = default_attention_config::<f32>(128, 8, 2, true);
+ let (expected, _) = run::<Cpu, f32>(config, KVCacheView::full(37), nodes, true);
+ let (actual, tolerance) = run::<Metal, f32>(config, KVCacheView::full(37), nodes, true);
+ assert_eq_float(&expected, &actual, tolerance, "INT8 f32 branching tree with 80 nodes");
+ for (causal, ring, window) in
+ [(true, false, None), (false, false, None), (true, true, Some(17)), (false, true, Some(17))]
+ {
+ let mut config = default_attention_config::<bf16>(256, 24, 4, causal);
+ config.has_sinks = true;
+ config.is_kv_cache_ring = ring;
+ config.sliding_window_size = window;
+ let cache = if ring {
+ KVCacheView::ring(37, 11)
+ } else {
+ KVCacheView::full(37)
+ };
+ for is_trie in [false, true] {
+ let (expected, _) = run::<Cpu, bf16>(config, cache, nodes, is_trie);
+ let (actual, tolerance) = run::<Metal, bf16>(config, cache, nodes, is_trie);
+ assert_eq_float(
+ &expected,
+ &actual,
+ tolerance,
+ &format!("INT8 BF16 80 nodes causal={causal} ring={ring} window={window:?} trie={is_trie}"),
+ );
+ }
+ }
+}
+
+#[uzu_test]
+fn attention_single_query() {
+ let nodes: &[TrieNode] = bytemuck::cast_slice::<[u32; 3], TrieNode>(&[[0, 0, 0]]);
+ for dim in [64, 128, 256, 512] {
+ for q_heads in [6, 8] {
+ for prefix in [0, 31, 32, 37, 1025] {
+ for ring in [false, true] {
+ let mut config = default_attention_config::<bf16>(dim, q_heads, 2, true);
+ config.has_sinks = true;
+ config.gate_row_stride = Some(q_heads as u32 * dim as u32 + 7);
+ config.is_kv_cache_ring = ring;
+ config.sliding_window_size = ring.then_some(17);
+ let cache = if ring {
+ KVCacheView::ring(
+ prefix,
+ if prefix > 0 {
+ 11
+ } else {
+ 0
+ },
+ )
+ } else {
+ KVCacheView::full(prefix)
+ };
+ let (expected, _) = run::<Cpu, bf16>(config, cache, nodes, false);
+ let (actual, tolerance) = run::<Metal, bf16>(config, cache, nodes, false);
+ assert_eq_float(
+ &expected,
+ &actual,
+ tolerance,
+ &format!("single-query INT8 D{dim} Q{q_heads} prefix={prefix} ring={ring}"),
+ );
+ }
+ }
+ }
+ }
+}
+
+#[uzu_test]
+fn attention_vector_partial_rows() {
+ let nodes: &[TrieNode] = bytemuck::cast_slice::<[u32; 3], TrieNode>(&[[0, 1, 0], [1, 1, 1]]);
+ for prefix in [17, 1031] {
+ for ring in [false, true] {
+ let mut config = default_attention_config::<f32>(128, 6, 3, true);
+ config.has_sinks = true;
+ config.gate_row_stride = Some(6 * 128 + 3);
+ config.is_kv_cache_ring = ring;
+ config.sliding_window_size = ring.then_some(19);
+ let cache = if ring {
+ KVCacheView::ring(prefix, 7)
+ } else {
+ KVCacheView::full(prefix)
+ };
+ let (expected, _) = run::<Cpu, f32>(config, cache, nodes, true);
+ let (actual, tolerance) = run::<Metal, f32>(config, cache, nodes, true);
+ assert_eq_float(&expected, &actual, tolerance, "INT8 vector partial rows, tree, F32, sinks and gate");
+ }
+ }
+}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_grouped_policy_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_grouped_policy_test.rs
deleted file mode 100644
index baa363990..000000000
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_grouped_policy_test.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-use uzu_engine_macros::uzu_test;
-
-use super::{MaskKind, SplitGeometry, choose_splits, int8_splits, select_head_dim_slices};
-
-fn geometry(head_dim: u32) -> SplitGeometry {
- let (num_q_heads, query_rows_per_threadgroup, num_groups) = if head_dim == 128 {
- (32, 64, 8)
- } else {
- (24, 32, 4)
- };
- SplitGeometry {
- head_dim,
- num_q_heads,
- num_groups,
- query_rows_per_threadgroup,
- block_k: 32,
- }
-}
-
-#[uzu_test]
-fn measured_and_fallback_boundaries() {
- for (cores, head_dim, suffix, kv, query_rows, use_mxu, expected) in [
- (40, 256, 2, 16_384, 32, true, 18),
- (40, 256, 8, 16_384, 32, true, 9),
- (40, 256, 12, 61_440, 32, true, 6),
- (40, 256, 16, 5_120, 32, true, 6),
- (40, 256, 32, 32_768, 32, true, 10),
- (40, 128, 64, 32_768, 64, true, 10),
- (40, 256, 17, 262_144, 32, true, 10),
- (40, 256, 128, 16_383, 32, true, 3),
- (40, 256, 16, 128, 32, true, 4),
- (10, 256, 32, 262_144, 32, true, 3),
- (10, 256, 128, 16_383, 32, true, 1),
- (10, 256, 1, 61_440, 8, false, 10),
- ] {
- let geometry = SplitGeometry {
- query_rows_per_threadgroup: query_rows,
- ..geometry(head_dim)
- };
- assert_eq!(choose_splits(geometry, suffix, kv, cores, use_mxu), expected);
- }
-}
-
-#[uzu_test]
-fn should_encode_boundaries() {
- for (head_dim, mask, suffix, kv, use_mxu, expected) in [
- (256, MaskKind::Causal, 1, 0, true, None),
- (256, MaskKind::Causal, 2, 0, true, Some(4)),
- (128, MaskKind::Trie, 64, 0, true, Some(2)),
- (128, MaskKind::Causal, 65, 0, true, None),
- (256, MaskKind::Causal, 1_024, 0, true, Some(4)),
- (256, MaskKind::Causal, 1_025, 0, true, None),
- (256, MaskKind::None, 1_024, 0, true, None),
- (256, MaskKind::Trie, 65, 0, true, None),
- (256, MaskKind::Causal, 1, 16_383, false, None),
- (256, MaskKind::Causal, 1, 16_384, false, Some(8)),
- (256, MaskKind::Causal, 2, 16_384, false, Some(4)),
- (256, MaskKind::Causal, 4, 16_384, false, Some(2)),
- (128, MaskKind::Causal, 1, 16_384, false, Some(4)),
- (128, MaskKind::Causal, 512, 30_719, false, None),
- (128, MaskKind::Causal, 512, 30_720, false, Some(1)),
- (256, MaskKind::Causal, 3, 61_440, false, None),
- (256, MaskKind::None, 1, 61_440, false, None),
- (256, MaskKind::Causal, 512, 61_439, false, None),
- (256, MaskKind::Causal, 512, 61_440, false, Some(2)),
- ] {
- assert_eq!(select_head_dim_slices(head_dim, mask, suffix, kv, use_mxu), expected);
- }
-}
-
-#[uzu_test]
-fn long_prefill_split_selection_boundaries() {
- for (suffix, kv, cores, use_mxu, expected) in [
- (1024, 16_383, 40, true, 1),
- (64, 61_440, 40, true, 5),
- (1024, 16_384, 40, true, 8),
- (256, 61_440, 40, true, 30),
- (1024, 20_480, 40, true, 10),
- (1024, 102_400, 40, true, 10),
- (512, 61_440, 10, false, 16),
- ] {
- assert_eq!(choose_splits(geometry(256), suffix, kv, cores, use_mxu), expected, "suffix={suffix}, kv={kv}");
- }
-
- let many_heads = SplitGeometry {
- num_q_heads: 240,
- ..geometry(256)
- };
- assert_eq!(choose_splits(many_heads, 1024, 61_440, 40, true), 1, "fewer than two prefill splits fit");
-}
-
-#[uzu_test]
-fn int8_small_suffix_split_cap() {
- for (suffix, kv, expected) in
- [(1, 30_720, 16), (1, 102_400, 16), (4, 61_440, 16), (8, 61_440, 62), (16, 61_440, 62)]
- {
- assert_eq!(int8_splits(32, 256, suffix, kv), expected, "suffix={suffix}, kv={kv}");
- }
-}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
deleted file mode 100644
index 5d8fad960..000000000
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
+++ /dev/null
@@ -1,240 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use futures::executor::block_on;
-use half::bf16;
-use num_traits::Float;
-use uzu_engine_macros::uzu_test;
-
-use super::super::FullPrecisionInput;
-use crate::{
- backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig},
- },
- cpu::Cpu,
- metal::Metal,
- },
- data_type::DataTypeRepr,
- encodable_block::mixer::attention::KVCacheView,
- tests::{
- assert::assert_eq_float,
- helpers::{buffer_to_vec, create_buffer, create_buffer_with_data},
- },
-};
-
-struct Input<T: DataTypeRepr + Float> {
- queries: Box<[T]>,
- keys: Box<[T]>,
- values: Box<[T]>,
- num_heads: usize,
- num_kv_heads: usize,
- sequence_length: usize,
- suffix_length: usize,
- head_dim: usize,
- do_causal: bool,
-}
-
-fn attention_config<T: DataTypeRepr + Float>(input: &Input<T>) -> AttentionKernelConfig {
- super::default_attention_config::<T>(input.head_dim, input.num_heads, input.num_kv_heads, input.do_causal)
-}
-
-fn get_test_data<T: DataTypeRepr + Float>(
- num_heads: usize,
- num_kv_heads: usize,
- sequence_length: usize,
- suffix_length: usize,
- head_dim: usize,
- do_causal: bool,
-) -> (Input<T>, Vec<T>) {
- let q_size = num_heads * suffix_length * head_dim;
- let mut queries = vec![T::zero(); q_size];
- for i in 0..q_size {
- queries[i] = T::from((i as f32 * 0.13 + 0.5).sin() * 0.5).unwrap();
- }
-
- let k_size = sequence_length * num_kv_heads * head_dim;
- let mut keys = vec![T::zero(); k_size];
- for i in 0..k_size {
- keys[i] = T::from((i as f32 * 0.07 + 1.0).cos() * 0.5).unwrap();
- }
-
- let v_size = sequence_length * num_kv_heads * head_dim;
- let mut values = vec![T::zero(); v_size];
- for i in 0..v_size {
- values[i] = T::from((i as f32 * 0.11 + 2.0).sin() * 0.5).unwrap();
- }
-
- let input = Input {
- queries: queries.into_boxed_slice(),
- keys: keys.into_boxed_slice(),
- values: values.into_boxed_slice(),
- num_heads,
- num_kv_heads,
- sequence_length,
- suffix_length,
- head_dim,
- do_causal,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: DataTypeRepr + Float, B: Backend>(fixture: &Input<T>) -> Vec<T> {
- let context = block_on(B::Context::new()).expect("Failed to create Context");
-
- let config = attention_config(fixture);
-
- let queries_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &fixture.queries);
- let keys_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &fixture.keys);
- let values_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &fixture.values);
-
- let segment_prefix_length = fixture.sequence_length - fixture.suffix_length;
- let input = AttentionInput::FullPrecision(FullPrecisionInput {
- queries: &queries_buffer,
- keys: &keys_buffer,
- values: &values_buffer,
- });
- let args = AttentionArguments {
- suffix_length: fixture.suffix_length as u32,
- trie: None::<&B::GlobalGpuBuffer>,
- sinks: None,
- cache: KVCacheView::full(segment_prefix_length as u32),
- gate: None::<&B::GlobalGpuBuffer>,
- };
-
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
- let kernel = <B::Kernels as Kernels>::AttentionKernel::new(context.as_ref(), config)
- .expect("Failed to create attention kernel");
- let pooled_output = kernel.encode(input, args, &mut command_buffer).expect("Failed to encode attention");
- let mut output_buffer =
- create_buffer::<B, T>(context.as_ref(), fixture.suffix_length * fixture.num_heads * fixture.head_dim);
- command_buffer.encode_copy(&pooled_output, &mut output_buffer);
- drop(pooled_output);
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
-
- buffer_to_vec::<B, T>(&context, &output_buffer)
-}
-
-fn get_gemm_output<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
- let context = block_on(<Metal as Backend>::Context::new()).expect("Failed to create Metal context");
- let config = attention_config(input);
- let queries = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.queries);
- let keys = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.keys);
- let values = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.values);
- let cache = KVCacheView::full((input.sequence_length - input.suffix_length) as u32);
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
- let pooled = super::gemm::AttentionGemm::new(&config)
- .encode(
- FullPrecisionInput {
- queries: &queries,
- keys: &keys,
- values: &values,
- },
- AttentionArguments {
- suffix_length: input.suffix_length as u32,
- trie: None::<&<Metal as Backend>::GlobalGpuBuffer>,
- sinks: None,
- cache,
- gate: None::<&<Metal as Backend>::GlobalGpuBuffer>,
- },
- &mut command_buffer,
- )
- .expect("Failed to encode AttentionGemm");
- let mut output =
- create_buffer::<Metal, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);
- command_buffer.encode_copy(&pooled, &mut output);
- drop(pooled);
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<Metal, T>(&context, &output)
-}
-
-fn test_internal<T: DataTypeRepr + Float + Debug + Display>(
- input: &Input<T>,
- expected: &[T],
-) {
- let eps = 1e-2;
-
- let output = get_gemm_output(input);
- let msg = format!(
- "AttentionGemm failed (heads={}, kv_heads={}, seq={}, suffix={}, head_dim={}, causal={})",
- input.num_heads,
- input.num_kv_heads,
- input.sequence_length,
- input.suffix_length,
- input.head_dim,
- input.do_causal,
- );
- assert_eq_float::<T>(expected, &output, eps, &msg);
-}
-
-fn test_basic<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(4, 4, 8, 1, 64, false);
- test_internal(&input, &expected);
-
- let (input, expected) = get_test_data::<T>(4, 4, 8, 4, 64, false);
- test_internal(&input, &expected);
-}
-
-fn test_causal<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(4, 4, 16, 1, 64, true);
- test_internal(&input, &expected);
-
- let (input, expected) = get_test_data::<T>(4, 4, 8, 4, 64, true);
- test_internal(&input, &expected);
-}
-
-fn test_gqa<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(8, 2, 8, 1, 64, false);
- test_internal(&input, &expected);
-
- let (input, expected) = get_test_data::<T>(8, 2, 8, 4, 64, true);
- test_internal(&input, &expected);
-}
-
-fn test_head_dim<T: DataTypeRepr + Float + Debug + Display>(head_dim: usize) {
- let (input, expected) = get_test_data::<T>(4, 4, 8, 2, head_dim, true);
- test_internal(&input, &expected);
-}
-
-fn test_unaligned<T: DataTypeRepr + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(4, 4, 40, 7, 64, true);
- test_internal(&input, &expected);
-
- let (input, expected) = get_test_data::<T>(4, 4, 13, 4, 64, false);
- test_internal(&input, &expected);
-}
-
-#[uzu_test]
-fn test_basic_bf16() {
- test_basic::<bf16>();
-}
-
-#[uzu_test]
-fn test_causal_bf16() {
- test_causal::<bf16>();
-}
-
-#[uzu_test]
-fn test_gqa_bf16() {
- test_gqa::<bf16>();
-}
-
-#[uzu_test]
-fn test_head_dim_128_bf16() {
- test_head_dim::<bf16>(128);
-}
-
-#[uzu_test]
-fn test_unaligned_bf16() {
- test_unaligned::<bf16>();
-}
-
-#[uzu_test]
-fn test_prefill_mxu() {
- let (input, expected) = get_test_data::<bf16>(4, 4, 128, 128, 64, true);
- test_internal(&input, &expected);
- let (input, expected) = get_test_data::<bf16>(8, 2, 100, 96, 128, true);
- test_internal(&input, &expected);
-}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
index aa8679a27..80e45225f 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
@@ -2,23 +2,21 @@ use futures::executor::block_on;
use half::bf16;
use uzu_engine_macros::uzu_test;
-use super::super::FullPrecisionInput;
use crate::{
backends::{
common::{
- Backend, BufferRef, CommandBufferEncoding, Context, Kernels,
+ Backend, CommandBufferEncoding, Context, Kernels,
gpu_types::trie::TrieNode as GpuTrieNode,
- kernel::{
- AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareInt8Kernel, Int8Input, KVFormat,
- SigmoidGateKernel,
- },
+ kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareKernel},
+ },
+ metal::{
+ Metal,
+ kernel::attention::{AttentionMetalKernel, tests::default_attention_config},
},
- cpu::Cpu,
- metal::Metal,
},
- data_type::{DataType, DataTypeRepr},
+ data_type::DataType,
encodable_block::{
- mixer::attention::{KVCacheView, kv_storage::KVStorage},
+ mixer::attention::{KVCache, KVCacheView},
sampling::PRng,
},
tests::{
@@ -30,389 +28,303 @@ use crate::{
type AttentionShape = (usize, usize, usize, usize, usize, bool);
-fn attention_data(shape: AttentionShape) -> (Vec<bf16>, Vec<bf16>) {
- let (head_dim, _, num_groups, suffix_length, prefix_length, _) = shape;
- let row = num_groups * head_dim;
- let count = (prefix_length + suffix_length) * row;
- (fill_attention(count, 1.0), fill_attention(count, 2.0))
-}
-
-fn fill_attention(
+pub(super) fn fill_attention(
count: usize,
phase: f32,
) -> Vec<bf16> {
(0..count).map(|i| bf16::from_f32(((i as f32) * 0.017 + phase).sin() * 0.5)).collect()
}
-fn run_attention<B: Backend>(
- context: &B::Context,
- shape: AttentionShape,
- trie_nodes: Option<&[GpuTrieNode]>,
- sinks_data: Option<&[bf16]>,
-) -> Vec<bf16> {
- let (keys, values) = attention_data(shape);
- let (head_dim, num_q_heads, num_groups, _, prefix_length, is_causal) = shape;
- let mut config = super::default_attention_config::<bf16>(head_dim, num_q_heads, num_groups, is_causal);
- config.has_sinks = sinks_data.is_some();
- let kernel = <B::Kernels as Kernels>::AttentionKernel::new(context, config).expect("attention kernel");
- run_attention_with_kernel::<B>(
- context,
- &kernel,
- shape,
- &keys,
- &values,
- KVCacheView::full(prefix_length as u32),
- trie_nodes,
- sinks_data,
- )
-}
-
-fn run_attention_with_kernel<B: Backend>(
- context: &B::Context,
- kernel: &<B::Kernels as Kernels>::AttentionKernel,
- shape: AttentionShape,
- keys_data: &[bf16],
- values_data: &[bf16],
- cache: KVCacheView,
- trie_nodes: Option<&[GpuTrieNode]>,
- sinks_data: Option<&[bf16]>,
-) -> Vec<bf16> {
- let (head_dim, num_q_heads, _, suffix_length, _, _) = shape;
- let queries =
- create_buffer_with_data::<B, bf16>(context, &fill_attention(num_q_heads * suffix_length * head_dim, 0.5));
- let keys = create_buffer_with_data::<B, bf16>(context, keys_data);
- let values = create_buffer_with_data::<B, bf16>(context, values_data);
- let sinks = sinks_data.map(|data| create_buffer_with_data::<B, bf16>(context, data));
- let trie = trie_nodes.map(|nodes| create_buffer_with_data::<B, u32>(context, bytemuck::cast_slice(nodes)));
- let input = AttentionInput::FullPrecision(FullPrecisionInput {
- queries: &queries,
- keys: &keys,
- values: &values,
- });
- let arguments = AttentionArguments {
- suffix_length: suffix_length as u32,
- trie: trie.as_ref(),
- sinks: sinks.as_ref(),
- cache,
- gate: None::<&B::GlobalGpuBuffer>,
- };
- let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");
- let pooled = kernel.encode(input, arguments, &mut command_buffer).expect("encode");
- let mut output = create_buffer::<B, bf16>(context, suffix_length * num_q_heads * head_dim);
- command_buffer.encode_copy(&pooled, &mut output);
- submit_command_buffer(command_buffer);
- buffer_to_vec::<B, bf16>(context, &output)
-}
-
#[uzu_test]
-fn attention_kernel_matches_cpu() {
- const TRIE_SUFFIX_LENGTH: usize = 31;
- let tokens: Vec<u64> = (0..TRIE_SUFFIX_LENGTH as u64).collect();
- let trie: Vec<GpuTrieNode> = TrieNode::flat(0, &tokens, &PRng::new(0)).linearize().token_subtrie_ranges().collect();
- let cpu_context = block_on(<Cpu as Backend>::Context::new()).expect("CPU attention context");
- let metal_context = block_on(<Metal as Backend>::Context::new()).expect("Metal attention context");
- for &(head_dim, num_q_heads, num_groups, suffix_length, prefix_length, causal, use_trie) in &[
- (128, 8, 2, 16, 1024, false, false),
- (256, 6, 1, 2, 1024, false, false),
- (256, 6, 1, 15, 2048, true, false),
- (256, 6, 1, 32, 1024, true, false),
- (256, 6, 1, TRIE_SUFFIX_LENGTH, 1024, true, true),
- (512, 8, 8, 1, 0, false, false),
- (512, 8, 8, 1, 1024, false, false),
- (64, 8, 8, 9, 0, false, false),
- (64, 4, 4, 8, 0, false, false),
- (64, 8, 2, 8, 0, false, false),
- (64, 8, 8, 8, 1024, false, false),
- (64, 8, 2, 8, 1024, false, false),
- (256, 24, 4, 1, 16_383, true, false),
- (256, 24, 4, 2, 16_383, true, false),
- (256, 24, 4, 4, 16_380, true, false),
- (128, 32, 8, 1, 16_383, true, false),
- (256, 6, 1, 512, 60_928, true, false),
- (256, 1, 1, 1024, 60_417, true, false),
- (128, 4, 1, 512, 30_208, true, false),
- (128, 4, 1, 1024, 29_696, true, false),
- (128, 8, 2, 512, 30_208, true, false),
- ] {
- let nodes = use_trie.then_some(trie.as_slice());
- let shape = (head_dim, num_q_heads, num_groups, suffix_length, prefix_length, causal);
- let expected = run_attention::<Cpu>(cpu_context.as_ref(), shape, nodes, None);
- let actual = run_attention::<Metal>(metal_context.as_ref(), shape, nodes, None);
- let label = format!("attention kernel D{head_dim} S{suffix_length} L{prefix_length} causal={causal}");
- assert_eq_float::<bf16>(&expected, &actual, 1e-2, &label);
- }
- for shape in [(512, 8, 2, 1, 32, false), (512, 8, 2, 1, 2048, false), (64, 4, 4, 64, 0, false)] {
- let sinks = vec![bf16::ONE; shape.1];
- let expected = run_attention::<Cpu>(cpu_context.as_ref(), shape, None, Some(&sinks));
- let actual = run_attention::<Metal>(metal_context.as_ref(), shape, None, Some(&sinks));
- assert_eq_float::<bf16>(&expected, &actual, 1e-2, "BF16 GQA with sinks");
- }
-}
-
-#[uzu_test]
-fn attention_kernel_reuses_instance_for_flat_and_trie() {
- let shape = (256, 6, 1, 5, 1024, true);
- let trie: Vec<GpuTrieNode> =
- TrieNode::flat(0, &[0, 1, 2, 3, 4], &PRng::new(0)).linearize().token_subtrie_ranges().collect();
- let context = block_on(<Metal as Backend>::Context::new()).expect("Metal attention context");
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AttentionKernel::new(
- context.as_ref(),
- super::default_attention_config::<bf16>(shape.0, shape.1, shape.2, shape.5),
- )
- .expect("attention kernel");
- let (keys, values) = attention_data(shape);
- let cache = KVCacheView::full(1024);
- let cpu = block_on(<Cpu as Backend>::Context::new()).expect("CPU attention context");
- for nodes in [None, Some(trie.as_slice())] {
- let expected = run_attention::<Cpu>(&cpu, shape, nodes, None);
- let actual = run_attention_with_kernel::<Metal>(&context, &kernel, shape, &keys, &values, cache, nodes, None);
- assert_eq_float::<bf16>(&expected, &actual, 1e-2, "reused flat/trie attention kernel");
- }
-}
-
-#[uzu_test]
-fn attention_kernel_ring_matches_full_on_wrap() {
- const HEAD_DIM: usize = 64;
- const NUM_HEADS: usize = 8;
- const CAPACITY: usize = 8;
- const CONTEXT: usize = 12;
- const SUFFIX: usize = 2;
- let shape = (HEAD_DIM, NUM_HEADS, NUM_HEADS, SUFFIX, CONTEXT, true);
- let row = NUM_HEADS * HEAD_DIM;
- let (full_keys, full_values) = attention_data(shape);
- let mut ring_keys = vec![bf16::ZERO; (CAPACITY + SUFFIX) * row];
- let mut ring_values = vec![bf16::ZERO; (CAPACITY + SUFFIX) * row];
- let ring_offset = (CONTEXT - CAPACITY) % CAPACITY;
- let rows = (0..CAPACITY)
- .map(|index| (CONTEXT - CAPACITY + index, (ring_offset + index) % CAPACITY))
- .chain((0..SUFFIX).map(|index| (CONTEXT + index, CAPACITY + index)));
- for (source, destination) in rows {
- for (full, ring) in [(&full_keys, &mut ring_keys), (&full_values, &mut ring_values)] {
- ring[destination * row..(destination + 1) * row].copy_from_slice(&full[source * row..(source + 1) * row]);
+fn attention_matches_cpu() {
+ let metal = block_on(<Metal as Backend>::Context::new()).unwrap();
+ type Prepare = <<Metal as Backend>::Kernels as Kernels>::AttentionPrepareKernel;
+ const NAN: u16 = bf16::NAN.to_bits();
+ const DENORMAL: u16 = 1; // 1 / scale overflows to inf
+ for use_mxu in [false, true].into_iter().filter(|&use_mxu| !use_mxu || metal.supports_mxu) {
+ // (query heads, suffix, prefix, trie, shared KV, unwritten scale bits)
+ for (q_heads, suffix, prefix, use_trie, reader, poison) in [
+ (8, 80, 16, false, false, NAN),
+ (8, 24, 37, false, false, NAN),
+ (8, 64, 0, true, false, NAN),
+ (64, 80, 16, false, false, NAN),
+ (24, 1, 1024, false, false, NAN),
+ (16, 16, 1024, false, false, DENORMAL),
+ (24, 80, 16, false, false, NAN),
+ (24, 3, 16, true, true, NAN),
+ (24, 8, 32, false, false, DENORMAL),
+ (16, 3, 37, true, false, DENORMAL),
+ (32, 1, 1024, false, false, NAN),
+ (32, 1024, 24, false, false, bf16::MAX.to_bits()),
+ (32, 3, 1024, true, false, bf16::INFINITY.to_bits()),
+ (24, 8, 0, true, false, NAN),
+ (24, 8, 4096, true, false, NAN),
+ (24, 8, 32768, true, false, DENORMAL),
+ (32, 8, 4097, true, false, NAN),
+ (24, 63, 29, true, false, NAN),
+ (24, 64, 0, true, false, NAN),
+ ] {
+ let (head_dim, kv_heads) = match q_heads {
+ 8 => (64, 2),
+ 32 => (128, 2),
+ 64 => (512, 4),
+ _ => (256, 4),
+ };
+ let tokens: Vec<u64> = (0..suffix as u64).collect();
+ let trie: Vec<GpuTrieNode> = if suffix == 8 {
+ // (start, end, height) per token
+ bytemuck::cast_slice::<[u32; 3], GpuTrieNode>(&[
+ [0, 7, 0],
+ [1, 3, 1],
+ [2, 2, 2],
+ [3, 3, 2],
+ [4, 7, 1],
+ [5, 6, 2],
+ [6, 6, 3],
+ [7, 7, 2],
+ ])
+ .to_vec()
+ } else {
+ TrieNode::flat(0, &tokens, &PRng::new(0)).linearize().token_subtrie_ranges().collect()
+ };
+ let (shape, nodes) =
+ ((head_dim, q_heads, kv_heads, suffix, prefix, true), use_trie.then_some(trie.as_slice()));
+ let mut config = default_attention_config::<bf16>(head_dim, q_heads, kv_heads, true);
+ let gate_stride = q_heads * head_dim + 17;
+ let gates = matches!(prefix, 37 | 4096).then(|| fill_attention(suffix * gate_stride, 3.0));
+ config.gate_row_stride = gates.as_ref().map(|_| gate_stride as u32);
+ let gate = gates.as_ref().map(|data| create_buffer_with_data::<Metal, bf16>(&metal, data));
+ let kernel = AttentionMetalKernel::new_with_mxu(&metal, &config, use_mxu).unwrap();
+ let (queries, keys, values) = attention_inputs(shape);
+ // Fused QKV rows from `attention_inputs`; its queries are head-major.
+ let stride = (q_heads + 2 * kv_heads) * head_dim;
+ let mut rows = vec![bf16::ZERO; (prefix + suffix) * stride];
+ for (row, (k, v)) in
+ rows.chunks_mut(stride).zip(keys.chunks(kv_heads * head_dim).zip(values.chunks(kv_heads * head_dim)))
+ {
+ let (key_row, value_row) = row[q_heads * head_dim..].split_at_mut(kv_heads * head_dim);
+ key_row.copy_from_slice(k);
+ value_row.copy_from_slice(v);
+ }
+ for (index, query) in queries.chunks(head_dim).enumerate() {
+ rows[(prefix + index % suffix) * stride + index / suffix * head_dim..][..head_dim]
+ .copy_from_slice(query);
+ }
+ let mut fill = metal.create_command_buffer(None, None).unwrap();
+ let mut kv =
+ KVCache::<Metal>::allocate_scratch(kernel.kv_layout(), (prefix + suffix).max(2048) as u32, &mut fill)
+ .unwrap();
+ let pattern =
+ create_buffer_with_data::<Metal, u16>(&metal, &vec![poison; kv.k_scales.size() / size_of::<bf16>()]);
+ for buffer in [&mut kv.k_codes, &mut kv.v_codes] {
+ fill.encode_fill(buffer.as_mut(), poison as u8);
+ }
+ for buffer in [&mut kv.k_scales, &mut kv.v_scales] {
+ fill.encode_copy(&pattern, buffer.as_mut());
+ }
+ submit_command_buffer(fill);
+ let mut step =
+ |rows: &[bf16], prefix: usize, trie: Option<&[GpuTrieNode]>, append_kv: bool, attend: bool| {
+ let suffix = rows.len() / stride;
+ let query_rows = q_heads / kv_heads * suffix;
+ let prepare = Prepare::new(
+ &metal,
+ DataType::BF16,
+ DataType::F32,
+ head_dim as u32,
+ false,
+ kv_heads as u32,
+ kernel.kv_layout().backend_opaque_layout,
+ append_kv,
+ false,
+ false,
+ false,
+ )
+ .unwrap();
+ let mut query_codes = create_buffer::<Metal, i8>(&metal, kv_heads * query_rows * head_dim);
+ let mut query_scales = create_buffer::<Metal, bf16>(&metal, kv_heads * query_rows);
+ let mut command_buffer = metal.create_command_buffer(None, None).unwrap();
+ let trie = trie.map(|nodes| command_buffer.allocate_constant_from_slice(nodes).unwrap());
+ prepare.encode(
+ &create_buffer_with_data::<Metal, bf16>(&metal, rows),
+ &mut query_codes,
+ &mut query_scales,
+ append_kv.then_some(kv.k_codes.as_mut()),
+ append_kv.then_some(kv.k_scales.as_mut()),
+ append_kv.then_some(kv.v_codes.as_mut()),
+ append_kv.then_some(kv.v_scales.as_mut()),
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ Default::default(),
+ q_heads as u32,
+ None,
+ prefix as u32,
+ stride as u32,
+ suffix as u32,
+ query_rows as u32,
+ &mut command_buffer,
+ );
+ if !attend {
+ submit_command_buffer(command_buffer);
+ return Vec::new();
+ }
+ let input = AttentionInput {
+ query_codes: &query_codes,
+ query_scales: &query_scales,
+ k_codes: kv.k_codes.as_ref(),
+ k_scales: kv.k_scales.as_ref(),
+ v_codes: kv.v_codes.as_ref(),
+ v_scales: kv.v_scales.as_ref(),
+ };
+ let arguments = AttentionArguments {
+ sinks: None,
+ suffix_length: suffix as u32,
+ trie: trie.as_ref(),
+ cache: KVCacheView::full(prefix as u32),
+ gate: gate.as_ref(),
+ };
+ let pooled = kernel.encode(input, arguments, &mut command_buffer).unwrap();
+ let mut output = create_buffer::<Metal, bf16>(&metal, suffix * q_heads * head_dim);
+ command_buffer.encode_copy(&pooled, &mut output);
+ drop((pooled, trie));
+ submit_command_buffer(command_buffer);
+ buffer_to_vec::<Metal, bf16>(&metal, &output)
+ };
+ if prefix > 0 {
+ step(&rows[..prefix * stride], 0, None, true, false);
+ }
+ let mut actual = step(&rows[prefix * stride..], prefix, nodes, true, true);
+ if reader {
+ // The reader's own K/V rows are junk: appending them would change the output.
+ rows[prefix * stride..].chunks_mut(stride).for_each(|row| row[q_heads * head_dim..].fill(bf16::ONE));
+ actual = step(&rows[prefix * stride..], prefix, nodes, false, true);
+ }
+ let label =
+ format!("int8 attention mxu={use_mxu} q{q_heads} S{suffix} L{prefix} trie={use_trie} reader={reader}");
+ let mut expected = quantized_attention_reference(shape, nodes);
+ if let Some(gates) = &gates {
+ for (token, row) in expected.chunks_exact_mut(q_heads * head_dim).enumerate() {
+ for (channel, value) in row.iter_mut().enumerate() {
+ *value = bf16::from_f32(
+ value.to_f32() / (1.0 + (-gates[token * gate_stride + channel].to_f32()).exp()),
+ );
+ }
+ }
+ }
+ assert_eq_float::<bf16>(
+ &expected,
+ &actual,
+ if use_mxu {
+ 1e-2
+ } else {
+ 5e-3
+ },
+ &label,
+ );
}
}
-
- let context = block_on(<Metal as Backend>::Context::new()).expect("Metal attention context");
- let mut config = super::default_attention_config::<bf16>(shape.0, shape.1, shape.2, shape.5);
- config.sliding_window_size = Some(CAPACITY as u32);
- let [full, ring] = [
- (&full_keys, &full_values, KVCacheView::full(CONTEXT as u32)),
- (&ring_keys, &ring_values, KVCacheView::ring(CAPACITY as u32, ring_offset as u32)),
- ]
- .map(|(keys, values, cache)| {
- config.is_kv_cache_ring = cache.ring_params().is_some();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AttentionKernel::new(&context, config).unwrap();
- run_attention_with_kernel::<Metal>(&context, &kernel, shape, keys, values, cache, None, None)
- });
- assert_eq_float::<bf16>(&full, &ring, 1e-2, "wrapped ring attention");
-}
-
-fn check_attention_gate<B: Backend>(
- context: &B::Context,
- suffix_length: usize,
- prefix_length: usize,
-) {
- const HEAD_DIM: usize = 256;
- const Q_HEADS: usize = 24;
- const KV_HEADS: usize = 4;
- const GATE_DIM: usize = Q_HEADS * HEAD_DIM;
- const PROJECTION_DIM: usize = 2 * (Q_HEADS + KV_HEADS) * HEAD_DIM;
- let mut config = super::default_attention_config::<bf16>(HEAD_DIM, Q_HEADS, KV_HEADS, true);
- let plain = <B::Kernels as Kernels>::AttentionKernel::new(context, config).expect("attention kernel");
- config.gate_row_stride = Some(PROJECTION_DIM as u32);
- let gated = <B::Kernels as Kernels>::AttentionKernel::new(context, config).expect("gated attention kernel");
- let sigmoid_gate =
- <B::Kernels as Kernels>::SigmoidGateKernel::new(context, bf16::data_type()).expect("sigmoid gate kernel");
- let shape = (HEAD_DIM, Q_HEADS, KV_HEADS, suffix_length, prefix_length, true);
- let (keys, values) = attention_data(shape);
- let queries = create_buffer_with_data::<B, bf16>(context, &fill_attention(Q_HEADS * suffix_length * HEAD_DIM, 0.5));
- let keys = create_buffer_with_data::<B, bf16>(context, &keys);
- let values = create_buffer_with_data::<B, bf16>(context, &values);
- let qkvg = create_buffer_with_data::<B, bf16>(context, &fill_attention(suffix_length * PROJECTION_DIM, 3.0));
- let input = AttentionInput::FullPrecision(FullPrecisionInput {
- queries: &queries,
- keys: &keys,
- values: &values,
- });
- let arguments = |gate| AttentionArguments {
- suffix_length: suffix_length as u32,
- trie: None::<&B::GlobalGpuBuffer>,
- sinks: None,
- cache: KVCacheView::full(prefix_length as u32),
- gate,
- };
- let gate_segment = qkvg.subrange((PROJECTION_DIM - GATE_DIM) * size_of::<bf16>()..);
- let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");
- let mut expected = plain.encode(input, arguments(None), &mut command_buffer).expect("plain attention");
- sigmoid_gate.encode(
- gate_segment,
- &mut expected,
- GATE_DIM as u32,
- suffix_length as u32,
- PROJECTION_DIM as u32,
- &mut command_buffer,
- );
- let fused = gated.encode(input, arguments(Some(gate_segment)), &mut command_buffer).expect("gated attention");
- let mut expected_out = create_buffer::<B, bf16>(context, suffix_length * GATE_DIM);
- let mut fused_out = create_buffer::<B, bf16>(context, suffix_length * GATE_DIM);
- command_buffer.encode_copy(&expected, &mut expected_out);
- command_buffer.encode_copy(&fused, &mut fused_out);
- submit_command_buffer(command_buffer);
- let expected = buffer_to_vec::<B, bf16>(context, &expected_out);
- let fused = buffer_to_vec::<B, bf16>(context, &fused_out);
- assert_eq!(expected, fused, "gated attention differs at S{suffix_length} L{prefix_length}");
}
-#[uzu_test]
-fn attention_gate_matches_standalone_gate_on_cpu() {
- let context = block_on(<Cpu as Backend>::Context::new()).expect("CPU attention context");
- check_attention_gate::<Cpu>(context.as_ref(), 3, 29);
-}
-
-#[uzu_test]
-fn attention_gate_matches_standalone_gate_on_metal() {
- let context = block_on(<Metal as Backend>::Context::new()).expect("Metal attention context");
- for (suffix_length, prefix_length) in
- [(1, 100), (1, 2000), (200, 800), (2, 1022), (16, 16368), (65, 959), (65, 16319), (1024, 0), (512, 60_928)]
- {
- check_attention_gate::<Metal>(context.as_ref(), suffix_length, prefix_length);
- }
+fn attention_inputs(shape: AttentionShape) -> (Vec<bf16>, Vec<bf16>, Vec<bf16>) {
+ use rand::{RngExt, SeedableRng, rngs::SmallRng};
+ let (dim, q_heads, kv_heads, suffix, prefix, _) = shape;
+ let mut rng = SmallRng::seed_from_u64(42);
+ let queries = (0..q_heads * suffix * dim).map(|_| bf16::from_f32(rng.random_range(-2.0..2.0))).collect();
+ let keys = (0..(prefix + suffix) * kv_heads * dim).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
+ let values = (0..(prefix + suffix) * kv_heads * dim)
+ .map(|i| bf16::from_f32(rng.random_range(-0.5..0.5) + 0.25 * (i % dim) as f32 / dim as f32))
+ .collect();
+ (queries, keys, values)
}
-#[uzu_test]
-fn int8_attention_matches_cpu() {
- let (metal, cpu) =
- (block_on(<Metal as Backend>::Context::new()).unwrap(), block_on(<Cpu as Backend>::Context::new()).unwrap());
- type Prepare = <<Metal as Backend>::Kernels as Kernels>::AttentionPrepareInt8Kernel;
- let trie: [GpuTrieNode; 3] = bytemuck::cast([0u32, 2, 0, 1, 1, 1, 2, 2, 1]); // (start, end, height) per token
- // (query heads, suffix, prefix, trie, shared KV, unwritten scale bits)
- const NAN: u16 = bf16::NAN.to_bits();
- const DENORMAL: u16 = 1; // 1 / scale overflows to inf
- for (q_heads, suffix, prefix, use_trie, reader, poison) in [
- (24, 1, 1024, false, false, NAN),
- (16, 16, 1024, false, false, DENORMAL),
- (24, 80, 16, false, false, NAN),
- (24, 3, 16, true, true, NAN),
- (24, 8, 32, false, false, DENORMAL),
- (16, 3, 37, true, false, DENORMAL),
- (32, 1, 1024, false, false, NAN),
- (32, 1024, 24, false, false, bf16::MAX.to_bits()),
- (32, 3, 1024, true, false, bf16::INFINITY.to_bits()),
- ] {
- let (head_dim, kv_heads) = if q_heads == 32 {
- (128, 2)
- } else {
- (256, 4)
- };
- let (shape, nodes) = ((head_dim, q_heads, kv_heads, suffix, prefix, true), use_trie.then_some(trie.as_slice()));
- let config = super::default_attention_config::<bf16>(head_dim, q_heads, kv_heads, true);
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AttentionKernel::new(&metal, config).unwrap();
- if !kernel.supports_int8() {
- return;
- }
- // Fused QKV rows over the data `run_attention` uses; its queries are head-major.
- let ((keys, values), stride) = (attention_data(shape), (q_heads + 2 * kv_heads) * head_dim);
- let mut rows = vec![bf16::ZERO; (prefix + suffix) * stride];
- for (row, (k, v)) in
- rows.chunks_mut(stride).zip(keys.chunks(kv_heads * head_dim).zip(values.chunks(kv_heads * head_dim)))
- {
- let (key_row, value_row) = row[q_heads * head_dim..].split_at_mut(kv_heads * head_dim);
- key_row.copy_from_slice(k);
- value_row.copy_from_slice(v);
- }
- for (index, query) in fill_attention(q_heads * suffix * head_dim, 0.5).chunks(head_dim).enumerate() {
- rows[(prefix + index % suffix) * stride + index / suffix * head_dim..][..head_dim].copy_from_slice(query);
- }
- let mut cache = KVStorage::<Metal>::create_empty(
- KVFormat::INT8,
- kv_heads as u32,
- head_dim as u32,
- 2048,
- DataType::BF16,
- &metal,
- )
- .unwrap();
- cache.prepare(2048).unwrap();
- let KVStorage::Int8(kv, _) = &mut cache else {
- unreachable!()
- };
- let mut fill = metal.create_command_buffer(None, None).unwrap();
- let pattern =
- create_buffer_with_data::<Metal, u16>(&metal, &vec![poison; kv.k_scales.size() / size_of::<bf16>()]);
- for buffer in [&mut kv.k_codes, &mut kv.v_codes] {
- fill.encode_fill(buffer.as_mut(), poison as u8);
+fn quantized_attention_reference(
+ shape: AttentionShape,
+ nodes: Option<&[GpuTrieNode]>,
+) -> Vec<bf16> {
+ use crate::backends::common::gpu_types::kv_layout;
+ fn hadamard_transform(row: &mut [f32]) {
+ let mut width = 1;
+ while width < row.len() {
+ for block in row.chunks_exact_mut(2 * width) {
+ let (left, right) = block.split_at_mut(width);
+ for (a, b) in left.iter_mut().zip(right) {
+ (*a, *b) = (*a + *b, *a - *b);
+ }
+ }
+ width *= 2;
}
- for buffer in [&mut kv.k_scales, &mut kv.v_scales] {
- fill.encode_copy(&pattern, buffer.as_mut());
+ let scale = (row.len() as f32).sqrt().recip();
+ row.iter_mut().for_each(|value| *value *= scale);
+ }
+ let (head_dim, q_heads, kv_heads, suffix, prefix, causal) = shape;
+ let signs: Vec<f32> = (0..head_dim)
+ .map(|channel| {
+ if kv_layout::ROTATION_SIGN_BITS[channel / 32 % 8] >> (channel % 32) & 1 == 0 {
+ 1.0
+ } else {
+ -1.0
+ }
+ })
+ .collect();
+ let quantize = |input: &[bf16]| {
+ let mut result = Vec::with_capacity(input.len());
+ for row in input.chunks_exact(head_dim) {
+ let mut rotated: Vec<f32> = row.iter().zip(&signs).map(|(value, sign)| value.to_f32() * sign).collect();
+ hadamard_transform(&mut rotated);
+ let maximum = rotated.iter().fold(0.0f32, |maximum, value| maximum.max(value.abs()));
+ let scale = bf16::from_f32(if maximum > 0.0 {
+ maximum / 127.0
+ } else {
+ 1.0
+ })
+ .to_f32();
+ result.extend(rotated.iter().map(|value| (value / scale).round_ties_even().clamp(-127.0, 127.0) * scale));
}
- submit_command_buffer(fill);
- let mut step = |rows: &[bf16], prefix: usize, trie: Option<&[GpuTrieNode]>, append_kv: bool| {
- let suffix = rows.len() / stride;
- let query_rows = q_heads / kv_heads * suffix;
- let prepare = Prepare::new(
- &metal,
- DataType::BF16,
- DataType::F32,
- head_dim as u32,
- false,
- true,
- kv_heads as u32,
- append_kv,
- )
- .unwrap();
- let mut query_codes = create_buffer::<Metal, i8>(&metal, kv_heads * query_rows * head_dim);
- let mut query_scales = create_buffer::<Metal, bf16>(&metal, kv_heads * query_rows);
- let mut command_buffer = metal.create_command_buffer(None, None).unwrap();
- let trie = trie.map(|nodes| command_buffer.allocate_constant_from_slice(nodes).unwrap());
- prepare.encode(
- &create_buffer_with_data::<Metal, bf16>(&metal, rows),
- None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
- Some(&mut query_codes),
- Some(&mut query_scales),
- append_kv.then_some(kv.k_codes.as_mut()),
- append_kv.then_some(kv.k_scales.as_mut()),
- append_kv.then_some(kv.v_codes.as_mut()),
- append_kv.then_some(kv.v_scales.as_mut()),
- None::<&<Metal as Backend>::GlobalGpuBuffer>,
- None::<&<Metal as Backend>::GlobalGpuBuffer>,
- q_heads as u32,
- None,
- prefix as u32,
- stride as u32,
- suffix as u32,
- query_rows as u32,
- &mut command_buffer,
- );
- let input = AttentionInput::Int8(Int8Input {
- query_codes: &query_codes,
- query_scales: &query_scales,
- k_codes: kv.k_codes.as_ref(),
- k_scales: kv.k_scales.as_ref(),
- v_codes: kv.v_codes.as_ref(),
- v_scales: kv.v_scales.as_ref(),
- });
- let arguments = AttentionArguments {
- sinks: None,
- suffix_length: suffix as u32,
- trie: trie.as_ref(),
- cache: KVCacheView::full(prefix as u32),
- gate: None::<&<Metal as Backend>::GlobalGpuBuffer>,
- };
- let pooled = kernel.encode(input, arguments, &mut command_buffer).unwrap();
- let mut output = create_buffer::<Metal, bf16>(&metal, suffix * q_heads * head_dim);
- command_buffer.encode_copy(&pooled, &mut output);
- drop((pooled, trie));
- submit_command_buffer(command_buffer);
- buffer_to_vec::<Metal, bf16>(&metal, &output)
- };
- step(&rows[..prefix * stride], 0, None, true);
- let mut actual = step(&rows[prefix * stride..], prefix, nodes, true);
- if reader {
- // The reader's own K/V rows are junk: appending them would change the output.
- rows[prefix * stride..].chunks_mut(stride).for_each(|row| row[q_heads * head_dim..].fill(bf16::ONE));
- actual = step(&rows[prefix * stride..], prefix, nodes, false);
+ result
+ };
+ let (queries, keys, values) = attention_inputs(shape);
+ let queries = quantize(&queries);
+ let keys = quantize(&keys);
+ let values = quantize(&values);
+ let length = prefix + suffix;
+ let scale = 1.0 / (head_dim as f32).sqrt();
+ let mut result = vec![0.0f32; suffix * q_heads * head_dim];
+ for head in 0..q_heads {
+ let kv_head = head / (q_heads / kv_heads);
+ for token in 0..suffix {
+ let query = &queries[(head * suffix + token) * head_dim..][..head_dim];
+ let mut scores = vec![f32::NEG_INFINITY; length];
+ for (key, score) in scores.iter_mut().enumerate() {
+ if causal && key >= prefix {
+ let visible = nodes.map_or(key - prefix <= token, |nodes| {
+ let ancestor = &nodes[key - prefix];
+ (ancestor.trie_start..=ancestor.trie_end).contains(&(token as u32))
+ });
+ if !visible {
+ continue;
+ }
+ }
+ let k = &keys[(key * kv_heads + kv_head) * head_dim..][..head_dim];
+ *score = query.iter().zip(k).map(|(q, k)| q * k).sum::<f32>() * scale;
+ }
+ let maximum = scores.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let weights: Vec<f32> = scores.iter().map(|score| (score - maximum).exp()).collect();
+ let denominator: f32 = weights.iter().sum();
+ let output = &mut result[(token * q_heads + head) * head_dim..][..head_dim];
+ for (key, weight) in weights.iter().enumerate() {
+ let v = &values[(key * kv_heads + kv_head) * head_dim..][..head_dim];
+ for (sum, value) in output.iter_mut().zip(v) {
+ *sum += weight * value / denominator;
+ }
+ }
}
- let label = format!("int8 attention q{q_heads} S{suffix} L{prefix} trie={use_trie} reader={reader}");
- assert_eq_float::<bf16>(&run_attention::<Cpu>(cpu.as_ref(), shape, nodes, None), &actual, 1e-2, &label);
}
+ for row in result.chunks_exact_mut(head_dim) {
+ hadamard_transform(row);
+ row.iter_mut().zip(&signs).for_each(|(value, sign)| *value *= sign);
+ }
+ result.into_iter().map(bf16::from_f32).collect()
}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs
index 2835a85f3..928ef392f 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs
@@ -1,9 +1,8 @@
#![cfg(backend = "metal")]
-use super::gemm;
use crate::{backends::common::kernel::AttentionKernelConfig, data_type::DataTypeRepr};
-mod gemm_test;
+mod cpu_comparison_test;
mod kernel_test;
fn default_attention_config<T: DataTypeRepr>(
diff --git a/crates/uzu-engine/unit/common/attention.rs b/crates/uzu-engine/unit/common/attention.rs
new file mode 100644
index 000000000..5244018fe
--- /dev/null
+++ b/crates/uzu-engine/unit/common/attention.rs
@@ -0,0 +1,31 @@
+use crate::{
+ backends::common::{
+ Backend, Kernels,
+ kernel::{AttentionKernel, AttentionKernelConfig, kv_layout::KVLayout},
+ },
+ data_type::DataType,
+};
+
+pub(crate) fn kv_layout<B: Backend>(
+ context: &B::Context,
+ head_dim: u32,
+ num_kv_heads: u32,
+) -> KVLayout {
+ <B::Kernels as Kernels>::AttentionKernel::new(
+ context,
+ AttentionKernelConfig {
+ head_dim,
+ num_groups: num_kv_heads,
+ num_q_heads: num_kv_heads,
+ has_sinks: false,
+ gate_row_stride: None,
+ is_kv_cache_ring: false,
+ is_causal: true,
+ sliding_window_size: None,
+ scale: None,
+ data_type: DataType::BF16,
+ },
+ )
+ .unwrap()
+ .kv_layout()
+}
diff --git a/crates/uzu-engine/unit/common/mod.rs b/crates/uzu-engine/unit/common/mod.rs
index 1e690cbdd..75631447c 100644
--- a/crates/uzu-engine/unit/common/mod.rs
+++ b/crates/uzu-engine/unit/common/mod.rs
@@ -2,6 +2,7 @@
compile_error!("uzu tests require cpu backend");
pub mod assert;
+pub(crate) mod attention;
pub mod cold_pool;
pub mod harness;
pub mod helpers;
diff --git a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs
deleted file mode 100644
index 755e8223d..000000000
--- a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-use futures::executor::block_on;
-use uzu_engine_macros::uzu_test;
-
-use super::{Head, QKVNorm};
-use crate::{
- backends::common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::QKVNormKernel,
- },
- config::normalization::{NormalizationConfig, UpcastMode},
- data_type::DataType,
- tests::{
- assert::assert_eq_float,
- helpers::{buffer_to_vec, create_buffer_with_data, create_context, for_each_backend},
- },
-};
-
-fn run_key_value_row_stride_test<B: Backend>() {
- const BATCH_SIZE: u32 = 2;
- const NUM_KV_HEADS: u32 = 2;
- const HEAD_DIM: u32 = 4;
- const ROW_WIDTH: u32 = 2 * NUM_KV_HEADS * HEAD_DIM;
- const EPSILON: f32 = 1e-6;
-
- let context = create_context::<B>();
- let config = NormalizationConfig {
- epsilon: EPSILON,
- scale_offset: None,
- upcast_mode: UpcastMode::OnlyNormalization,
- subtract_mean: false,
- has_scale: false,
- has_biases: false,
- };
- let key = Head {
- kernel: <B::Kernels as Kernels>::QKVNormKernel::new(
- &context,
- DataType::F32,
- DataType::F32,
- DataType::F32,
- DataType::F32,
- true,
- false,
- )
- .expect("failed to construct key norm"),
- scales: None,
- config,
- };
- let norm = QKVNorm {
- query: None,
- key: Some(key),
- value: None,
- num_q_heads: 0,
- num_kv_heads: Some(NUM_KV_HEADS),
- projection_row_stride: ROW_WIDTH,
- head_dim: HEAD_DIM,
- };
-
- let row_width = ROW_WIDTH as usize;
- let head_dim = HEAD_DIM as usize;
- let input = (0..BATCH_SIZE as usize * row_width).map(|index| 1.0 + index as f32 * 0.125).collect::<Vec<_>>();
- let mut expected = input.clone();
- for batch in 0..BATCH_SIZE as usize {
- for head in 0..NUM_KV_HEADS as usize {
- let start = batch * row_width + head * head_dim;
- let mean_square =
- input[start..start + head_dim].iter().map(|value| value * value).sum::<f32>() / HEAD_DIM as f32;
- let inverse_rms = (mean_square + EPSILON).sqrt().recip();
- for index in start..start + head_dim {
- expected[index] *= inverse_rms;
- }
- }
- }
-
- let mut key_value = create_buffer_with_data::<B, f32>(&context, &input);
- let mut command_buffer = context.create_command_buffer(None, None).expect("failed to create command buffer");
- norm.encode_key_value(&mut key_value, BATCH_SIZE, &mut command_buffer);
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("failed to execute key/value norm");
-
- let output = buffer_to_vec::<B, f32>(&context, &key_value);
- assert_eq_float(&expected, &output, 1e-5, "key/value norm row stride mismatch");
-}
-
-#[uzu_test]
-fn test_key_value_norm_uses_element_row_stride() {
- for_each_backend!(|B| run_key_value_row_stride_test::<B>());
-}
diff --git a/scripts/clang-format.sh b/scripts/clang-format.sh
index 1e8892113..c0fa4a3ec 100755
--- a/scripts/clang-format.sh
+++ b/scripts/clang-format.sh
@@ -30,7 +30,9 @@ fi
# - untracked files that are not ignored
FILES=()
while IFS= read -r -d '' file; do
- FILES+=("$file")
+ if [[ -f "$file" ]]; then
+ FILES+=("$file")
+ fi
done < <(git ls-files -z --cached --others --exclude-standard -- \
'*.h' '*.hpp' '*.hh' \
'*.c' '*.cc' '*.cpp' \