Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

INT8 KV cache wiring, grouped attention kernel (#943)

CCYeh72286062d735
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 2bbfa5c6d..324cb11d4 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,4 +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;
diff --git a/crates/uzu-engine/src/backends/common/kernel/attention.rs b/crates/uzu-engine/src/backends/common/kernel/attention.rs
index 2f696060a..22f14a53d 100644
--- a/crates/uzu-engine/src/backends/common/kernel/attention.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/attention.rs
@@ -6,6 +6,12 @@ use crate::{
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;
@@ -15,14 +21,20 @@ pub trait AttentionKernel: Sized + Send + Sync {
config: AttentionKernelConfig,
) -> Result<Self, Self::Error>;
+ fn supports_int8(&self) -> bool {
+ false
+ }
+
fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Self::Backend,
+ input: AttentionInput<
impl BufferRef<Backend = Self::Backend>,
impl BufferRef<Backend = Self::Backend>,
impl BufferRef<Backend = Self::Backend>,
+ >,
+ arguments: AttentionArguments<
+ '_,
+ Self::Backend,
impl BufferRef<Backend = Self::Backend>,
impl BufferRef<Backend = Self::Backend>,
>,
@@ -44,21 +56,33 @@ pub struct AttentionKernelConfig {
pub data_type: DataType,
}
-pub struct AttentionArguments<
- 'a,
- B: Backend,
- QT: BufferRef<Backend = B>,
- TT: BufferRef<Backend = B>,
- KT: BufferRef<Backend = B>,
- VT: BufferRef<Backend = B>,
- GT: BufferRef<Backend = B>,
-> {
- pub queries: QT,
- pub keys: KT,
- pub values: VT,
+pub struct AttentionArguments<'a, B: Backend, TT: BufferRef<Backend = B>, GT: BufferRef<Backend = B>> {
pub suffix_length: u32,
pub trie: Option<TT>,
pub sinks: Option<&'a B::GlobalBuffer>,
pub cache: KVCacheView,
pub gate: Option<GT>,
}
+
+#[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 query_codes: QT,
+ pub query_scales: QT,
+ pub k_codes: KT,
+ pub k_scales: KT,
+ pub v_codes: VT,
+ pub v_scales: VT,
+}
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 7ffc660f2..c672dadd8 100644
--- a/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/kv_layout.rs
@@ -1,3 +1,5 @@
+use half::bf16;
+
use crate::backends::common::gpu_types::kv_layout;
pub struct Int8KVLayout {
@@ -17,6 +19,7 @@ impl Int8KVLayout {
}
/// Scales: [key block][head][key in block].
+ #[cfg(backend = "cpu")]
pub fn scale_index(
&self,
key: u32,
@@ -26,6 +29,21 @@ impl Int8KVLayout {
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
+ }
+
+ pub fn scale_bytes(
+ &self,
+ keys: u32,
+ ) -> usize {
+ self.code_bytes(keys) / self.head_dim as usize * size_of::<bf16>()
+ }
+
+ #[cfg(backend = "cpu")]
pub fn k_code_index(
&self,
key: u32,
@@ -40,6 +58,7 @@ impl Int8KVLayout {
as usize
}
+ #[cfg(backend = "cpu")]
pub fn v_code_index(
&self,
key: u32,
@@ -60,6 +79,7 @@ impl Int8KVLayout {
}
}
+#[cfg(backend = "cpu")]
fn mma_lane(
row: u32,
group: u32,
diff --git a/crates/uzu-engine/src/backends/common/kernel/mod.rs b/crates/uzu-engine/src/backends/common/kernel/mod.rs
index e1206e9d5..03ea2eb09 100644
--- a/crates/uzu-engine/src/backends/common/kernel/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/mod.rs
@@ -8,7 +8,6 @@ pub mod attention;
pub mod delta_net_chunked_prefill;
pub mod delta_net_tree_verify;
pub mod gated_act_mul;
-#[cfg(any(backend = "cpu", test))]
pub mod kv_layout;
pub mod matmul;
pub mod radix_top_k_small;
@@ -16,7 +15,9 @@ pub mod radix_top_k_small;
mod trellis;
pub use activation_transform::{ActivationQuantization, ActivationTransform};
-pub use attention::{AttentionArguments, AttentionKernel, AttentionKernelConfig};
+pub use attention::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, FullPrecisionInput, Int8Input, KVFormat,
+};
pub use gated_act_mul::{GatedActMul, GatedActMulSettings};
#[cfg(any(backend = "cpu", test))]
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 ab202b81f..bb9b0135d 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs
@@ -14,7 +14,8 @@ use crate::backends::{
common::{
BufferRef, CommandBufferEncoding,
kernel::{
- AttentionArguments, AttentionKernel, AttentionKernelConfig, AttentionSinglePassKernel, SigmoidGateKernel,
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, AttentionSinglePassKernel,
+ SigmoidGateKernel,
},
},
cpu::{Cpu, command_buffer::CpuCommandBufferEncoding, context::CpuContext, error::CpuError},
@@ -39,17 +40,17 @@ impl AttentionKernel for AttentionCpuKernel {
fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Cpu,
- impl BufferRef<Backend = Cpu>,
- impl BufferRef<Backend = Cpu>,
+ 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>>,
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],
@@ -69,9 +70,9 @@ impl AttentionKernel for AttentionCpuKernel {
{
let command_buffer = &mut *command_buffer.debug_group("attention core");
single_pass.encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
+ input.queries,
+ input.keys,
+ input.values,
&mut output,
config.num_q_heads / config.num_groups,
arguments.cache.prefix_len() + arguments.suffix_length,
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
index 2b251a10e..ad7150121 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare_int8.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/prepare_int8.rs
@@ -20,10 +20,10 @@ pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRep
#[optional(!quantize_queries)] queries: Option<*mut ElementT>,
#[optional(quantize_queries)] q_codes: Option<*mut i8>,
#[optional(quantize_queries)] q_scales: Option<*mut ElementT>,
- k_codes: *mut i8,
- k_scales: *mut ElementT,
- v_codes: *mut u8,
- v_scales: *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,
@@ -31,10 +31,11 @@ pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRep
kv_token_offset: u32,
input_row_stride: u32,
suffix_length: u32,
- padded_suffix: 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 {
@@ -44,27 +45,21 @@ pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRep
};
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, Some(k_scales)),
- _ => (head - v_head_start, Some(v_scales)),
+ (_, true) => (head - num_q_heads, k_scales),
+ _ => (head - v_head_start, v_scales),
};
- for token in 0..padded_suffix {
- let query_row = (head * padded_suffix + token) as usize;
- if token >= suffix_length {
- if is_query && quantize_queries {
- unsafe {
- std::ptr::write_bytes(q_codes.unwrap().add(query_row * head_dim), 0, head_dim);
- *scales.unwrap().add(query_row) = ElementT::one();
- }
- }
- continue;
- }
+ 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 {
@@ -99,7 +94,7 @@ pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRep
})
.unwrap();
let scale_index = if is_query {
- query_row
+ ((head / gqa_factor) * query_rows + (head % gqa_factor) * suffix_length + token) as usize
} else {
layout.scale_index(kv_token_offset + token, kv_head)
};
@@ -109,9 +104,10 @@ pub fn attention_prepare_int8<ElementT: DataTypeRepr + Float, RopeT: DataTypeRep
if is_query {
*q_codes.unwrap().add(scale_index * head_dim + channel) = code;
} else if is_key {
- *k_codes.add(layout.k_code_index(kv_token_offset + token, kv_head, channel as u32)) = code;
+ *k_codes.unwrap().add(layout.k_code_index(kv_token_offset + token, kv_head, channel as u32)) =
+ code;
} else {
- *v_codes.add(layout.v_code_index(kv_token_offset + token, kv_head, channel as u32)) =
+ *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;
}
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
index 6835bc9ce..da31d80d2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
@@ -1,6 +1,7 @@
#include <metal_stdlib>
#include "../common/activation_quantization.h"
#include "../common/defines.h"
+#include "../common/conversion.h"
#include "../common/dsl.h"
#include "../common/thread_context.h"
#include "../generated/activation_transform.h"
@@ -68,7 +69,7 @@ PUBLIC KERNEL(ActivationTransform)(
if (in_bounds) {
if (has_bias) {
if constexpr (metal::is_same_v<T, bfloat>) {
- values = as_type<float4>(uint4(as_type<ushort4>(vec<bfloat, HADAMARD_VECTOR_SIZE>(values))) << 16);
+ values = uzu::bfloat_to_float(vec<bfloat, HADAMARD_VECTOR_SIZE>(values));
}
values += float4(load_hadamard_vector(bias + first_index));
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs
index f31b769a4..bc08b4091 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/error.rs
@@ -4,6 +4,8 @@ use crate::backends::metal::{error::MetalError, kernel::matmul::MatmulMetalError
#[derive(Debug, Error)]
pub enum AttentionMetalError {
+ #[error("INT8 KV unsupported for this attention config")]
+ UnsupportedInt8KV,
#[error("Backend error: {0}")]
Backend(#[from] MetalError),
#[error("Matmul error: {0}")]
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs
index b7bd69ab4..df9b885cf 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs
@@ -1,5 +1,6 @@
use parking_lot::Mutex;
+use super::FullPrecisionInput;
use crate::{
backends::{
common::{
@@ -82,15 +83,12 @@ impl AttentionFallback {
pub fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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, AttentionMetalError> {
assert!(arguments.trie.is_none(), "fallback does not support trie");
@@ -112,11 +110,11 @@ impl AttentionFallback {
self.matmul.lock().encode(
MatmulArguments {
a: MatmulA::FullPrecision {
- values: arguments.queries,
+ values: input.queries,
offset: group_index as usize * group_rows * head_dim_bytes,
},
b: MatmulB::FullPrecision {
- b: arguments.keys.subrange(group_index as usize * head_dim_bytes..),
+ b: input.keys.subrange(group_index as usize * head_dim_bytes..),
},
b_leading_dimension: Some(self.num_groups * self.head_dim),
b_transpose: true,
@@ -167,7 +165,7 @@ impl AttentionFallback {
offset: group_index as usize * group_rows * sequence_length as usize * dt_bytes,
},
b: MatmulB::FullPrecision {
- b: arguments.values.subrange(group_index as usize * head_dim_bytes..),
+ b: input.values.subrange(group_index as usize * head_dim_bytes..),
},
b_leading_dimension: Some(self.num_groups * self.head_dim),
b_transpose: false,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs
index 78c035fb2..a403cc7d4 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs
@@ -2,6 +2,7 @@ use std::collections::{HashMap, hash_map::Entry};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
+use super::FullPrecisionInput;
use crate::{
backends::{
common::{
@@ -112,15 +113,12 @@ impl AttentionGemm {
pub fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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
@@ -161,9 +159,9 @@ impl AttentionGemm {
};
let kernel = self.get_or_create(command_buffer.context(), key)?;
kernel.encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
+ input.queries,
+ input.keys,
+ input.values,
&mut output,
params,
arguments.cache.ring_params(),
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_gemm_grouped.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal
similarity index 69%
rename from crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_gemm_grouped.metal
rename to crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal
index 2aeb9fbfd..d61c7029c 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_gemm_grouped.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention.metal
@@ -7,54 +7,13 @@
#include "../../matmul/common/mxu_fragment/ops.h"
#include "../../generated/attention.h"
#include "../../generated/trie.h"
-#include "../attention_gate.h"
+#include "util.h"
using namespace metal;
using namespace uzu::matmul;
using namespace uzu::attention;
using namespace uzu::trie;
-#define ATTENTION_GQA_SIMDGROUPS 8
-
-template <typename T, uint BK, uint BD, uint D_SLICES>
-struct AttentionGemmGroupedLayout {
- using Ops = MxuFragmentOps<>;
-
- UZU_CONST int SIMDGROUPS = ATTENTION_GQA_SIMDGROUPS;
- UZU_CONST int TILE_ROWS = Ops::FRAGMENT_ROWS;
- UZU_CONST int SLICE_COLS = int(BD) / int(D_SLICES);
- UZU_CONST int BANDS = SIMDGROUPS / int(D_SLICES);
- UZU_CONST int BLOCK_ROWS = BANDS * TILE_ROWS;
- UZU_CONST int SCORE_TILE_ELEMENTS = TILE_ROWS * int(BK);
- UZU_CONST int SCORE_EXCHANGE_SIZE = SIMDGROUPS * SCORE_TILE_ELEMENTS;
-};
-
-template <class FragmentType, class Fn>
-METAL_FUNC void map_lane_rows(thread FragmentType& tile, const short2 position, Fn fn) {
- using Ops = typename FragmentType::FragmentOpsType;
- using Element = typename FragmentType::ElementType;
- static_assert(FragmentType::ROW_FRAGMENTS == 1, "requires one row fragment");
- static_assert(
- Ops::THREAD_ELEMENT_ROWS * Ops::THREAD_ELEMENT_COLS == Ops::ELEMENTS_PER_THREAD,
- "requires row-major thread elements"
- );
-
- thread Element* data = tile.elements();
- METAL_PRAGMA_UNROLL
- for (ushort fragment_col = 0; fragment_col < FragmentType::COL_FRAGMENTS; ++fragment_col) {
- const ushort fragment_base = fragment_col * Ops::ELEMENTS_PER_THREAD;
- const short col_base = position.x + short(fragment_col) * short(Ops::FRAGMENT_COLS);
- METAL_PRAGMA_UNROLL
- for (ushort row = 0; row < Ops::THREAD_ELEMENT_ROWS; ++row) {
- METAL_PRAGMA_UNROLL
- for (ushort col = 0; col < Ops::THREAD_ELEMENT_COLS; ++col) {
- const ushort element = fragment_base + row * Ops::THREAD_ELEMENT_COLS + col;
- data[element] = Element(fn(row, col_base + short(col), data[element]));
- }
- }
- }
-}
-
// TODO: support more BD and should tune more to replace AttentionGEMM
template <typename T, uint BK, uint BD, uint D_SLICES>
VARIANTS(T, bfloat)
@@ -72,21 +31,19 @@ KERNEL(AttentionGemmGrouped)(
device float* partial_sums OPTIONAL(split_kv),
const device TrieNode* trie OPTIONAL(is_trie),
const constant AttnParams& params,
- const constant uint& m_tiles,
+ const constant uint& query_tiles,
const constant uint& kv_heads,
- const constant uint& batch_count,
const constant uint& num_splits,
const bool split_kv SPECIALIZE,
const bool is_causal SPECIALIZE,
const bool is_trie SPECIALIZE,
- threadgroup float score_exchange[AttentionGemmGroupedLayout<T, BK, BD, D_SLICES>::SCORE_EXCHANGE_SIZE],
+ threadgroup float score_exchange[AttentionGemmGroupedLayout<BK, BD, D_SLICES>::SCORE_EXCHANGE_SIZE],
const ThreadContext thread_context,
- const uint tile_split_flat GROUPS(m_tiles * num_splits),
+ const uint tile_split_flat GROUPS(query_tiles * num_splits),
const uint kv_head_idx GROUPS(kv_heads),
- const uint batch_idx GROUPS(batch_count),
const uint lid THREADS(ATTENTION_GQA_SIMDGROUPS * METAL_SIMD_SIZE)
) {
- using Layout = AttentionGemmGroupedLayout<T, BK, BD, D_SLICES>;
+ using Layout = AttentionGemmGroupedLayout<BK, BD, D_SLICES>;
using Ops = typename Layout::Ops;
using AccumType = float;
@@ -114,11 +71,11 @@ KERNEL(AttentionGemmGrouped)(
const ushort band = simdgroup_index / ushort(D_SLICES);
const ushort slice = simdgroup_index % ushort(D_SLICES);
- const uint m_tile_idx = split_kv ? (tile_split_flat % m_tiles) : tile_split_flat;
- const uint split_idx = split_kv ? (tile_split_flat / m_tiles) : 0u;
+ 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 row_base = m_tile_idx * uint(BLOCK_ROWS) + uint(band) * uint(TILE_ROWS);
+ const uint row_base = query_tile_idx * uint(BLOCK_ROWS) + uint(band) * uint(TILE_ROWS);
const uint head_in_group = row_base / params.q_len;
const uint query_base = row_base - head_in_group * params.q_len;
const uint q_head_idx = kv_head_idx * params.gqa_factor + head_in_group;
@@ -129,10 +86,9 @@ KERNEL(AttentionGemmGrouped)(
const uint output_row_stride = params.o_strides[2];
const uint slice_offset = uint(slice) * uint(SLICE_COLS);
- q += size_t(batch_idx) * params.q_strides[0] + size_t(q_head_idx) * params.q_strides[1] +
- size_t(query_base) * query_row_stride + slice_offset;
- k += size_t(batch_idx) * params.k_strides[0] + size_t(kv_head_idx) * params.k_strides[1] + slice_offset;
- v += size_t(batch_idx) * params.v_strides[0] + size_t(kv_head_idx) * params.v_strides[1] + slice_offset;
+ 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];
{
@@ -208,7 +164,7 @@ KERNEL(AttentionGemmGrouped)(
uint block_end = split_kv ? ((split_idx + 1u) * params.nk) / num_splits : params.nk;
if (is_causal) {
- const uint tile_first_row = m_tile_idx * uint(BLOCK_ROWS);
+ 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 = (tile_first_row / params.q_len == tile_last_row / params.q_len)
? (tile_last_row % params.q_len)
@@ -338,7 +294,7 @@ KERNEL(AttentionGemmGrouped)(
}
if (split_kv) {
- const uint tile_index = ((batch_idx * kv_heads + kv_head_idx) * m_tiles + m_tile_idx) * num_splits + split_idx;
+ const uint tile_index = (split_idx * kv_heads + kv_head_idx) * query_tiles + query_tile_idx;
device float* partial_tile = partials + size_t(tile_index) * BLOCK_ROWS * BD + size_t(band) * TILE_ROWS * BD;
output.store(lane, partial_tile + slice_offset, int(BD));
@@ -362,11 +318,10 @@ KERNEL(AttentionGemmGrouped)(
}
output.map_rows(inverse_sum, [](AccumType value, AccumType s) { return value * s; });
- device T* output_base = o + size_t(batch_idx) * params.o_strides[0];
if (params.q_len % uint(TILE_ROWS) == 0u) {
if (row_base < grouped_rows) {
- device T* destination = output_base + size_t(q_head_idx) * params.o_strides[1] +
- size_t(query_base) * output_row_stride + slice_offset;
+ 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 {
@@ -378,8 +333,7 @@ KERNEL(AttentionGemmGrouped)(
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 = output_base +
- (size_t(kv_head_idx) * params.gqa_factor + row_head) * params.o_strides[1] +
+ 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) {
@@ -394,70 +348,3 @@ KERNEL(AttentionGemmGrouped)(
}
}
}
-
-template <typename T, uint BD>
-VARIANTS(T, bfloat)
-VARIANTS(BD, 128, 256)
-KERNEL(AttentionGemmGroupedCombine)(
- const device float* 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& block_rows,
- const constant uint& m_tiles,
- const constant uint& kv_heads,
- const constant uint& batch_count,
- 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 batch_idx GROUPS(batch_count),
- const uint column THREADS(BD)
-) {
- const uint m_tile_idx = grouped_row_idx / block_rows;
- const uint row_in_tile = grouped_row_idx - m_tile_idx * block_rows;
- const uint tile_base = ((batch_idx * kv_heads + kv_head_idx) * m_tiles + m_tile_idx) * num_splits;
-
- const device float* row_maxs = partial_maxs + size_t(tile_base) * block_rows + row_in_tile;
- const device float* row_sums = partial_sums + size_t(tile_base) * block_rows + row_in_tile;
- const device float* row_partials = partials + size_t(tile_base) * block_rows * BD + size_t(row_in_tile) * BD + column;
-
- float global_max = -INFINITY;
- for (uint s = 0; s < num_splits; ++s) {
- if (row_sums[s * block_rows] > 0.0f) {
- global_max = metal::max(global_max, row_maxs[s * block_rows]);
- }
- }
-
- float numerator = 0.0f;
- float denominator = 0.0f;
- if (global_max > -INFINITY) {
- for (uint s = 0; s < num_splits; ++s) {
- const float split_sum = row_sums[s * block_rows];
- if (split_sum <= 0.0f) {
- continue;
- }
- const float rescale = fast::exp2(row_maxs[s * block_rows] - global_max);
- denominator += rescale * split_sum;
- numerator += rescale * row_partials[size_t(s) * block_rows * BD];
- }
- }
-
- 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;
- T result = static_cast<T>(denominator > 0.0f ? numerator / denominator : 0.0f);
- if (has_gate) {
- result = attention_apply_gate(
- result,
- gate[(batch_idx * params.q_len + query_position) * gate_row_stride + q_head_idx * BD + column]
- );
- }
- o += size_t(batch_idx) * params.o_strides[0] + 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/attention_int8.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_int8.metal
new file mode 100644
index 000000000..8abe1be58
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/attention_int8.metal
@@ -0,0 +1,528 @@
+#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 "util.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>;
+
+ // 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 TRIE_MASKS = Layout::BLOCK_ROWS;
+
+ 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;
+};
+
+template <class Ops, int DEPTH_FRAGMENTS>
+METAL_FUNC void prepare_queries(
+ const device int8_t* query_codes,
+ threadgroup uint4* staged_query,
+ uint query_row_base,
+ uint num_query_rows,
+ uint query_row_stride,
+ uint lane,
+ uint channel_slice
+) {
+ // Padding rows reread the last real row.
+ const short2 query_position = Ops::get_position(lane);
+ const uint query_row = query_row_base + uint(query_position.y);
+ const uint last_query_row = num_query_rows - 1u;
+ const device int8_t* query_row0 =
+ query_codes + size_t(min(query_row, last_query_row)) * query_row_stride + uint(query_position.x);
+ const device int8_t* query_row1 =
+ query_codes + size_t(min(query_row + uint(Ops::THREAD_ELEMENT_ROW_STRIDE), last_query_row)) * query_row_stride +
+ uint(query_position.x);
+ constexpr int SLICE_PAIRS = DEPTH_FRAGMENTS / 2;
+ METAL_PRAGMA_UNROLL
+ for (int slice_pair = 0; slice_pair < SLICE_PAIRS; ++slice_pair) {
+ const int query_fragment = (int(channel_slice) * SLICE_PAIRS + slice_pair) * 2;
+ uint4 packed_queries;
+ packed_queries.x = *reinterpret_cast<const device uint*>(query_row0 + query_fragment * int(Ops::FRAGMENT_ROWS));
+ packed_queries.y = *reinterpret_cast<const device uint*>(query_row1 + query_fragment * int(Ops::FRAGMENT_ROWS));
+ packed_queries.z =
+ *reinterpret_cast<const device uint*>(query_row0 + (query_fragment + 1) * int(Ops::FRAGMENT_ROWS));
+ packed_queries.w =
+ *reinterpret_cast<const device uint*>(query_row1 + (query_fragment + 1) * int(Ops::FRAGMENT_ROWS));
+ staged_query[(int(channel_slice) * SLICE_PAIRS + slice_pair) * METAL_SIMD_SIZE] = packed_queries;
+ }
+}
+
+template <class OutputFragment>
+struct Int8Softmax {
+ 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).
+ UZU_CONST AccumType RESCALE_THRESHOLD = 8.0f;
+
+ OutputFragment output;
+ AccumType running_max[ROWS_PER_LANE] = {
+ metal::numeric_limits<AccumType>::lowest(),
+ metal::numeric_limits<AccumType>::lowest()
+ };
+ AccumType denominator[ROWS_PER_LANE] = {};
+ AccumType value_bias[ROWS_PER_LANE] = {};
+
+ METAL_FUNC Int8Softmax() { 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]};
+ for (uint published_block = 0; published_block < blocks_in_step; ++published_block) {
+ const float4 block_stats = slot_stats[published_block * stat_rows];
+ step_max[0] = metal::max(step_max[0], block_stats.x);
+ step_max[1] = metal::max(step_max[1], block_stats.z);
+ }
+ if (step_max[0] > running_max[0] + RESCALE_THRESHOLD || step_max[1] > running_max[1] + RESCALE_THRESHOLD) {
+ AccumType rescale[ROWS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (int row = 0; row < ROWS_PER_LANE; ++row) {
+ const AccumType next_max =
+ step_max[row] > running_max[row] + RESCALE_THRESHOLD ? step_max[row] : running_max[row];
+ rescale[row] = fast::exp2(running_max[row] - next_max);
+ running_max[row] = next_max;
+ denominator[row] *= rescale[row];
+ value_bias[row] *= rescale[row];
+ }
+ output.map_rows(rescale, [](AccumType value, AccumType factor) UZU_ALWAYS_INLINE { return value * factor; });
+ }
+ }
+
+ METAL_FUNC void normalize() thread {
+ output.map_rows(value_bias, [](AccumType value, AccumType bias) UZU_ALWAYS_INLINE { return value - bias; });
+
+ AccumType inverse_denominator[ROWS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (int row = 0; row < ROWS_PER_LANE; ++row) {
+ inverse_denominator[row] = denominator[row] > AccumType(0) ? AccumType(1) / denominator[row] : AccumType(1);
+ }
+ output.map_rows(inverse_denominator, [](AccumType value, AccumType inverse_sum) UZU_ALWAYS_INLINE {
+ return value * inverse_sum;
+ });
+ }
+};
+
+template <typename ScaleType, uint HEAD_DIM>
+VARIANTS(ScaleType, bfloat)
+VARIANTS(HEAD_DIM, 256)
+KERNEL(AttentionGemmGroupedInt8)(
+ 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),
+ 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 trie_masks[Int8Scratch<HEAD_DIM>::TRIE_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)
+) {
+ using Layout = AttentionGemmGroupedLayout<uzu::kv_layout::TILE_KEYS, HEAD_DIM, HEAD_DIM / uzu::kv_layout::SLICE_DIMS>;
+ using Scratch = Int8Scratch<HEAD_DIM>;
+ using Ops = typename Layout::Ops;
+ using AccumType = float;
+
+ constexpr uint DEPTH_SLICES = HEAD_DIM / uzu::kv_layout::SLICE_DIMS;
+
+ constexpr int KEY_FRAGMENTS = int(uzu::kv_layout::TILE_KEYS) / Ops::FRAGMENT_COLS;
+ constexpr int DEPTH_FRAGMENTS = Layout::SLICE_COLS / Ops::FRAGMENT_ROWS;
+ constexpr int VALUE_FRAGMENTS = Layout::SLICE_COLS / Ops::FRAGMENT_COLS;
+ constexpr int FRAGMENTS_PER_PANEL = 2;
+ constexpr int VALUE_PANELS = VALUE_FRAGMENTS / FRAGMENTS_PER_PANEL;
+ constexpr int ROWS_PER_LANE = Ops::THREAD_ELEMENT_ROWS;
+ constexpr int KEYS_PER_LANE = KEY_FRAGMENTS * Ops::THREAD_ELEMENT_COLS;
+ constexpr uint STAT_ROWS = uint(Layout::TILE_ROWS / ROWS_PER_LANE);
+
+ static_assert(KEY_FRAGMENTS == 2, "probabilities pack two key fragments");
+ static_assert(ROWS_PER_LANE == 2, "stats pack two rows per lane");
+
+ // P is stored as u8: p_code = rint(255 * exp2(scores - block_max)), so p = p_code / 255.
+ constexpr AccumType PROBABILITY_CODE_MAX = static_cast<AccumType>(metal::numeric_limits<uchar>::max());
+
+ using ScoreFragment = Fragment<AccumType, 1, KEY_FRAGMENTS, Ops>;
+ using ProbabilityFragment = Fragment<uchar, 1, KEY_FRAGMENTS, Ops>;
+
+ const ushort lane = ushort(thread_context.simd_lane_id);
+ const ushort query_band = ushort(thread_context.simdgroup_index) / ushort(DEPTH_SLICES);
+ const ushort channel_slice = ushort(thread_context.simdgroup_index) % ushort(DEPTH_SLICES);
+
+ const uint query_tile_index = tile_split_index % query_tiles;
+ const uint split_index = split_base + tile_split_index / query_tiles;
+
+ const uint num_query_rows = params.gqa_factor * params.q_len;
+ const uint query_row_base = query_tile_index * uint(Layout::BLOCK_ROWS) + uint(query_band) * uint(Layout::TILE_ROWS);
+
+ const uint channel_offset = uint(channel_slice) * uint(Layout::SLICE_COLS);
+
+ const size_t query_group_offset = size_t(kv_head_index) * params.q_strides[1];
+ query_codes += query_group_offset;
+ key_codes += uint(uzu::kv_layout::TILE_KEYS) * size_t(kv_head_index) * params.k_strides[1];
+ key_codes += int(lane) * uzu::kv_layout::LANE_BYTES;
+ const device uchar* value_tiles =
+ value_codes +
+ (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;
+
+ const uint prefix_length = params.q_off;
+ const uint key_length = params.k_len;
+ const short2 score_position = ScoreFragment::get_position(lane);
+ const uint lane_rows[ROWS_PER_LANE] = {
+ uint(score_position.y),
+ uint(score_position.y) + uint(Ops::THREAD_ELEMENT_ROW_STRIDE)
+ };
+ const uint query_band_offset = uint(query_band) * uint(Layout::TILE_ROWS);
+ uint query_positions[ROWS_PER_LANE];
+ if (!mask_free) {
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
+ query_positions[row] = (query_row_base + lane_rows[row]) % params.q_len;
+ }
+ if (is_trie) {
+ ulong row_trie_mask[ROWS_PER_LANE] = {};
+ for (uint node_index = 0; node_index < trie_nodes; ++node_index) {
+ const uzu::trie::TrieNode node = trie[node_index];
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
+ if (query_positions[row] >= node.trie_start && query_positions[row] <= node.trie_end) {
+ row_trie_mask[row] |= (1ul << node_index);
+ }
+ }
+ }
+ if (score_position.x == 0) {
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
+ trie_masks[query_band_offset + lane_rows[row]] = row_trie_mask[row];
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ }
+
+ const uint key_block_stride = uint(uzu::kv_layout::TILE_KEYS) * params.k_strides[2];
+ const uint value_block_stride = uint(uzu::kv_layout::TILE_KEYS) * params.v_strides[2];
+
+ const uint first_block = (split_index * params.nk) / num_splits;
+ const uint tile_first_row = query_tile_index * uint(Layout::BLOCK_ROWS);
+ const uint tile_last_row = min(tile_first_row + uint(Layout::BLOCK_ROWS) - 1u, num_query_rows - 1u);
+ 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 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;
+ const uint first_key = first_block * uint(uzu::kv_layout::TILE_KEYS);
+
+ 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 device ScaleType* block_key_scales = key_scales + first_scale_index;
+ const device ScaleType* block_value_scales = value_scales + first_scale_index;
+
+ AccumType query_score_scales[ROWS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (int row = 0; row < ROWS_PER_LANE; ++row) {
+ const uint query_row = min(query_row_base + lane_rows[row], num_query_rows - 1u);
+ query_score_scales[row] = AccumType(query_scales[query_group_offset / HEAD_DIM + query_row]) * log2_attention_scale;
+ }
+
+ threadgroup uchar* code_slot = reinterpret_cast<threadgroup uchar*>(probability_exchange);
+ threadgroup float* stat_slot = probability_exchange + Scratch::STATS_OFFSET;
+ const ushort band_first_simdgroup = query_band * ushort(int(DEPTH_SLICES));
+
+ threadgroup uchar* const lane_codes = code_slot + uint(band_first_simdgroup) * uint(Layout::SCORE_TILE_ELEMENTS) +
+ uint(lane) * uzu::kv_layout::LANE_BYTES;
+ threadgroup float4* const lane_stats = reinterpret_cast<threadgroup float4*>(stat_slot) +
+ uint(band_first_simdgroup) * STAT_ROWS + uint(score_position.y);
+ threadgroup float2* const lane_sums =
+ reinterpret_cast<threadgroup float2*>(probability_exchange + Scratch::SUMS_OFFSET) +
+ uint(band_first_simdgroup) * STAT_ROWS + uint(score_position.y);
+ uint slot_offset = 0u;
+ uint block_scale_offset = uint(channel_slice) * scales_per_block + uint(score_position.x);
+
+ threadgroup uint4* const staged_query =
+ query_stage + uint(query_band) * uint(Scratch::QUERY_VECTORS_PER_BAND) + uint(lane);
+ auto compute_probabilities = [&](uint block_index,
+ uint channel_slice,
+ threadgroup float4* slot_stats,
+ 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;
+
+ // Q x K^T (int8).
+ Fragment<int, 1, KEY_FRAGMENTS, Ops> score;
+ score.clear();
+ for (int depth_slice = 0; depth_slice < int(DEPTH_SLICES); ++depth_slice) {
+ METAL_PRAGMA_UNROLL
+ for (int slice_fragment = 0; slice_fragment < DEPTH_FRAGMENTS; slice_fragment += 2) {
+ const int depth_fragment = depth_slice * DEPTH_FRAGMENTS + slice_fragment;
+ using CodeVector = typename Ops::template ThreadVector<int8_t>;
+ OperandFragment<int8_t, 1, 2, Ops> query_fragments;
+ const uint4 packed_queries = staged_query[(depth_fragment / 2) * METAL_SIMD_SIZE];
+ query_fragments.fragment_data[0] = as_type<CodeVector>(packed_queries.xy);
+ query_fragments.fragment_data[1] = as_type<CodeVector>(packed_queries.zw);
+ OperandFragment<int8_t, 2, 2, Ops, ReadTranspose> key_fragments;
+ METAL_PRAGMA_UNROLL
+ for (int pair_index = 0; pair_index < 2; ++pair_index) {
+ const uint4 packed_keys = *reinterpret_cast<const device uint4*>(
+ block_keys + (depth_fragment + pair_index) * int(uzu::kv_layout::FRAGMENT_BYTES)
+ );
+ key_fragments.fragment_data[pair_index] = as_type<CodeVector>(uint2(packed_keys.x, packed_keys.y));
+ key_fragments.fragment_data[2 + pair_index] = as_type<CodeVector>(uint2(packed_keys.z, packed_keys.w));
+ }
+ simdgroup_barrier(mem_flags::mem_none);
+ fragment_mma(score, query_fragments, key_fragments);
+ }
+ }
+
+ // Dequantize scores to log2 units.
+ AccumType key_scale_values[KEYS_PER_LANE];
+ AccumType log2_value_scales[KEYS_PER_LANE];
+ AccumType inverse_value_scales[KEYS_PER_LANE];
+ {
+ const device ScaleType* lane_key_scales = block_key_scales + block_scale_offset;
+ const device ScaleType* lane_value_scales = block_value_scales + block_scale_offset;
+ METAL_PRAGMA_UNROLL
+ for (int fragment_col = 0; fragment_col < KEY_FRAGMENTS; ++fragment_col) {
+ METAL_PRAGMA_UNROLL
+ 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;
+ 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;
+ inverse_value_scales[lane_col] = valid ? metal::precise::divide(1.0f, value_scale) : 0.0f;
+ }
+ }
+ }
+ 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]
+ );
+ },
+ score
+ );
+
+ if (!mask_free && (is_tail_block || (key_base + uint(uzu::kv_layout::TILE_KEYS) > prefix_length))) {
+ ulong trie_row_masks[ROWS_PER_LANE] = {0ul, 0ul};
+ if (is_trie) {
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < ROWS_PER_LANE; ++row) {
+ trie_row_masks[row] = trie_masks[query_band_offset + lane_rows[row]];
+ }
+ }
+ map_lane_rows(scores, score_position, [&](ushort lane_row, short column, AccumType value) UZU_ALWAYS_INLINE {
+ const uint key = key_base + uint(column);
+ bool visible = key < key_length;
+ if (is_trie) {
+ visible = visible &&
+ (key < prefix_length || ((trie_row_masks[lane_row] >> ulong(key - prefix_length)) & 1ul) != 0ul);
+ } else {
+ visible = visible && key <= prefix_length + query_positions[lane_row];
+ }
+ return visible ? value : -metal::numeric_limits<AccumType>::infinity();
+ });
+ }
+
+ // Quantize probabilities and reduce row statistics.
+ AccumType block_max[ROWS_PER_LANE];
+ AccumType probability_code_sum[ROWS_PER_LANE];
+ ProbabilityFragment probability_codes;
+ scores.row_reduce(
+ block_max,
+ metal::numeric_limits<AccumType>::lowest(),
+ [](AccumType a, AccumType b) UZU_ALWAYS_INLINE { return metal::max(a, b); }
+ );
+ scores.for_each_lane(
+ [&](ushort row, ushort column, thread AccumType& value, thread uchar& code) UZU_ALWAYS_INLINE {
+ value = metal::rint(fast::exp2(value - (block_max[row] - metal::log2(PROBABILITY_CODE_MAX))));
+ code = uzu::round_to_byte(value);
+ },
+ probability_codes
+ );
+ scores.row_reduce(probability_code_sum, AccumType(0), [](AccumType a, AccumType b) UZU_ALWAYS_INLINE {
+ return a + b;
+ });
+ AccumType denominator_sum[ROWS_PER_LANE];
+ scores.for_each_lane([&](ushort row, ushort column, thread AccumType& value)
+ UZU_ALWAYS_INLINE { value *= inverse_value_scales[column]; });
+ scores.row_reduce(denominator_sum, AccumType(0), [](AccumType a, AccumType b) UZU_ALWAYS_INLINE { return a + b; });
+
+ // Publish probabilities and row statistics.
+ *reinterpret_cast<threadgroup uint4*>(slot_codes + uint(channel_slice) * uint(Layout::SCORE_TILE_ELEMENTS)) =
+ uint4(as_type<uint2>(probability_codes.fragment_data[0]), as_type<uint2>(probability_codes.fragment_data[1]));
+ if (score_position.x == 0) {
+ slot_stats[uint(channel_slice) * STAT_ROWS] =
+ float4(block_max[0], probability_code_sum[0], block_max[1], probability_code_sum[1]);
+ slot_sums[uint(channel_slice) * STAT_ROWS] = float2(denominator_sum[0], denominator_sum[1]);
+ }
+ };
+
+ auto accumulate_output = [&](uint block_index,
+ uint blocks_in_step,
+ threadgroup float4* slot_stats,
+ threadgroup float2* slot_sums,
+ threadgroup uchar* slot_codes) UZU_ALWAYS_INLINE {
+ // P x V over the published blocks.
+ for (uint published_block = 0; published_block < blocks_in_step; ++published_block) {
+ const float4 block_stats = slot_stats[published_block * STAT_ROWS];
+ const AccumType block_max[ROWS_PER_LANE] = {block_stats.x, block_stats.z};
+ 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};
+ AccumType block_weights[ROWS_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (int row = 0; row < ROWS_PER_LANE; ++row) {
+ block_weights[row] = fast::exp2(block_max[row] - softmax.running_max[row]) * (1.0f / PROBABILITY_CODE_MAX);
+ softmax.denominator[row] += block_weights[row] * denominator_sum[row];
+ softmax.value_bias[row] +=
+ block_weights[row] * AccumType(uzu::kv_layout::V_CODE_BIAS) * probability_code_sum[row];
+ softmax.value_bias[row] += block_weights[row] * uzu::FLOAT_OFFSET;
+ }
+
+ ProbabilityFragment probability_codes;
+ const uint4 packed_codes =
+ *reinterpret_cast<const threadgroup uint4*>(slot_codes + published_block * Layout::SCORE_TILE_ELEMENTS);
+ probability_codes.fragment_data[0] = as_type<typename ProbabilityFragment::ThreadVectorType>(packed_codes.xy);
+ probability_codes.fragment_data[1] = as_type<typename ProbabilityFragment::ThreadVectorType>(packed_codes.zw);
+
+ const uint value_block_index = block_index + published_block;
+ thread AccumType* output_elements = softmax.output.elements();
+ // Accumulate V panels directly into their output columns.
+ using ValueVector = typename Ops::template ThreadVector<uchar>;
+ const device uchar* block_values = value_tiles + value_block_index * value_block_stride;
+ METAL_PRAGMA_UNROLL
+ for (int panel = 0; panel < VALUE_PANELS; ++panel) {
+ OperandFragment<uchar, KEY_FRAGMENTS, FRAGMENTS_PER_PANEL, Ops> value_fragments;
+ METAL_PRAGMA_UNROLL
+ for (int key_fragment = 0; key_fragment < KEY_FRAGMENTS; ++key_fragment) {
+ const uint4 packed_values = *reinterpret_cast<const device uint4*>(
+ block_values + (key_fragment * VALUE_PANELS + panel) * uzu::kv_layout::FRAGMENT_BYTES
+ );
+ value_fragments.fragment_data[key_fragment * FRAGMENTS_PER_PANEL] = as_type<ValueVector>(packed_values.xy);
+ value_fragments.fragment_data[key_fragment * FRAGMENTS_PER_PANEL + 1] =
+ as_type<ValueVector>(packed_values.zw);
+ }
+ simdgroup_barrier(mem_flags::mem_none);
+ Fragment<int, 1, FRAGMENTS_PER_PANEL, Ops> product;
+ product.clear();
+ fragment_mma(product, probability_codes, value_fragments);
+ thread int* product_elements = product.elements();
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < Ops::THREAD_ELEMENT_ROWS; ++row) {
+ const AccumType block_weight = block_weights[row];
+ METAL_PRAGMA_UNROLL
+ for (ushort value_fragment = 0; value_fragment < FRAGMENTS_PER_PANEL; ++value_fragment) {
+ METAL_PRAGMA_UNROLL
+ for (ushort column = 0; column < Ops::THREAD_ELEMENT_COLS; ++column) {
+ const ushort panel_element_index =
+ value_fragment * Ops::ELEMENTS_PER_THREAD + row * Ops::THREAD_ELEMENT_COLS + column;
+ const ushort output_element_index =
+ (panel * FRAGMENTS_PER_PANEL + value_fragment) * Ops::ELEMENTS_PER_THREAD +
+ row * Ops::THREAD_ELEMENT_COLS + column;
+ const AccumType value = uzu::float_with_offset(product_elements[panel_element_index]);
+ output_elements[output_element_index] =
+ metal::fma(block_weight, value, output_elements[output_element_index]);
+ }
+ }
+ }
+ }
+ }
+ };
+
+ prepare_queries<Ops, DEPTH_FRAGMENTS>(
+ query_codes,
+ staged_query,
+ query_row_base,
+ num_query_rows,
+ params.q_strides[2],
+ lane,
+ channel_slice
+ );
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Per step, each depth-slice simdgroup scores one key block and publishes P; then all accumulate P x V.
+ uint block_index = 0;
+ while (block_index < block_count) {
+ const uint blocks_in_step = min(uint(int(DEPTH_SLICES)), block_count - block_index);
+ threadgroup float4* slot_stats = lane_stats + slot_offset / 4u;
+ threadgroup float2* slot_sums = lane_sums + slot_offset / 2u;
+ threadgroup uchar* slot_codes = lane_codes + 4u * slot_offset;
+
+ if (uint(channel_slice) < blocks_in_step) {
+ compute_probabilities(block_index, channel_slice, slot_stats, slot_sums, slot_codes);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ softmax.rescale(slot_stats, blocks_in_step, STAT_ROWS);
+
+ accumulate_output(block_index, blocks_in_step, slot_stats, slot_sums, slot_codes);
+
+ // Alternate slots to avoid a second barrier.
+ slot_offset = uint(Scratch::SLOT_FLOATS) - slot_offset;
+ block_index += blocks_in_step;
+ block_scale_offset += blocks_in_step * scales_per_block;
+ }
+
+ softmax.normalize();
+
+ const uint partial_tile_index =
+ ((split_index - split_base) * num_kv_heads + kv_head_index) * query_tiles + query_tile_index;
+ const size_t partial_offset = size_t(partial_tile_index) * Layout::BLOCK_ROWS * HEAD_DIM +
+ size_t(query_band) * Layout::TILE_ROWS * HEAD_DIM + channel_offset;
+ softmax.output.store(lane, partial_values + partial_offset, int(HEAD_DIM));
+
+ if (channel_slice == 0 && score_position.x == 0) {
+ METAL_PRAGMA_UNROLL
+ for (int row = 0; row < ROWS_PER_LANE; ++row) {
+ const uint row_index = partial_tile_index * uint(Layout::BLOCK_ROWS) + query_band_offset + lane_rows[row];
+ partial_maxima[row_index] = softmax.running_max[row];
+ partial_denominators[row_index] = softmax.denominator[row];
+ }
+ }
+}
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
new file mode 100644
index 000000000..1a70e2f0b
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine.metal
@@ -0,0 +1,65 @@
+#include <metal_stdlib>
+#include "../../common/dsl.h"
+#include "../../generated/attention.h"
+#include "../attention_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 float* 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 float* 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 * 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 = attention_apply_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/combine_int8.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine_int8.metal
new file mode 100644
index 000000000..7259b82d6
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/combine_int8.metal
@@ -0,0 +1,101 @@
+#include <metal_stdlib>
+#include "../../common/dsl.h"
+#include "../../generated/attention.h"
+#include "../../hadamard_transform/hadamard_transform.h"
+#include "../attention_gate.h"
+#include "../kv_layout.h"
+
+using namespace metal;
+
+template <typename T, uint BD>
+VARIANTS(T, bfloat)
+VARIANTS(BD, 256)
+KERNEL(AttentionGemmGroupedInt8Combine)(
+ 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 constant uzu::attention::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,
+ threadgroup float rotation[BD],
+ 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 bfloat* row_means = partials + row * BD + column;
+
+ float numerator = 0.0f;
+ float denominator = 0.0f;
+ constexpr uint SIMDGROUPS = BD / METAL_SIMD_SIZE;
+ float global_max = -metal::numeric_limits<float>::infinity();
+ 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]);
+ }
+ }
+ global_max = simd_max(global_max);
+ if (column % METAL_SIMD_SIZE == 0) {
+ rotation[column / METAL_SIMD_SIZE] = global_max;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ global_max = rotation[0];
+ for (uint simdgroup = 1; simdgroup < SIMDGROUPS; ++simdgroup) {
+ global_max = metal::max(global_max, rotation[simdgroup]);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ threadgroup float* split_weights = rotation;
+ for (uint chunk_start = 0; chunk_start < num_splits; chunk_start += BD) {
+ const uint split = chunk_start + column;
+ float weight = 0.0f;
+ if (split < num_splits && row_sums[split * split_rows] > 0.0f) {
+ weight = fast::exp2(row_maxs[split * split_rows] - global_max) * row_sums[split * split_rows];
+ }
+ split_weights[column] = weight;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ const uint chunk_size = metal::min(num_splits - chunk_start, uint(BD));
+ _Pragma("clang loop unroll_count(8)") for (uint i = 0; i < chunk_size; ++i) {
+ const float split_weight = split_weights[i];
+ denominator += split_weight;
+ numerator += split_weight * float(row_means[size_t(chunk_start + i) * split_rows * BD]);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ const float mean = denominator > 0.0f ? numerator / denominator : 0.0f;
+
+ rotation[column] = mean;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (column >= METAL_SIMD_SIZE) {
+ return;
+ }
+ constexpr ushort VALUES_PER_LANE = BD / METAL_SIMD_SIZE;
+ float rotated[VALUES_PER_LANE];
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ rotated[value_index] = rotation[value_index * METAL_SIMD_SIZE + column];
+ }
+ simdgroup_hadamard_transform<VALUES_PER_LANE, METAL_SIMD_SIZE>(ushort(column), rotated);
+ device T* output_row = o + size_t(q_head_idx) * params.o_strides[1] + size_t(query_position) * params.o_strides[2];
+ METAL_PRAGMA_UNROLL
+ for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
+ const uint channel = value_index * METAL_SIMD_SIZE + column;
+ T result = static_cast<T>(rotated[value_index] * uzu::kv_layout::rotation_sign(channel));
+ if (has_gate) {
+ result = attention_apply_gate(result, gate[query_position * gate_row_stride + q_head_idx * BD + channel]);
+ }
+ output_row[channel] = result;
+ }
+}
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
index 89f3f39ed..25ccfad65 100644
--- 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
@@ -1,5 +1,6 @@
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
+use super::FullPrecisionInput;
use crate::{
backends::{
common::{
@@ -18,7 +19,7 @@ use crate::{
data_type::DataType,
};
-mod policy;
+pub(super) mod policy;
use policy::{MAX_TRIE_SUFFIX, SplitGeometry, choose_splits};
use super::MaskKind;
@@ -93,16 +94,13 @@ impl AttentionGemmGroupedMetal {
gate: Option<impl BufferRef<Backend = Metal>>,
suffix_length: u32,
kv_length: u32,
- q_replicas: 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 m_tiles = grouped_rows.div_ceil(self.block_rows);
+ let query_tiles = grouped_rows.div_ceil(self.block_rows);
assert_eq!(trie.is_some(), self.mask.is_trie(), "trie presence must match mask");
- assert!(num_splits >= 1, "num_splits must be at least one");
- assert!(num_splits <= params.nk, "num_splits must not exceed KV blocks");
if num_splits == 1 {
self.kernel.encode(
@@ -115,16 +113,15 @@ impl AttentionGemmGroupedMetal {
None::<&mut <Metal as Backend>::ScratchBuffer>,
trie,
params,
- m_tiles,
+ query_tiles,
self.num_groups,
- q_replicas,
1,
command_buffer,
);
return Ok(false);
}
- let partial_rows = q_replicas * self.num_groups * m_tiles * num_splits * self.block_rows;
+ let partial_rows = self.num_groups * query_tiles * num_splits * self.block_rows;
let mut partials = command_buffer.allocate_scratch_for_shape(&[partial_rows, self.head_dim], DataType::F32)?;
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)?;
@@ -139,9 +136,8 @@ impl AttentionGemmGroupedMetal {
Some(&mut partial_sums),
trie,
params,
- m_tiles,
+ query_tiles,
self.num_groups,
- q_replicas,
num_splits,
command_buffer,
);
@@ -154,10 +150,8 @@ impl AttentionGemmGroupedMetal {
gate,
params,
grouped_rows,
- self.block_rows,
- m_tiles,
+ query_tiles * self.block_rows,
self.num_groups,
- q_replicas,
num_splits,
self.gate_row_stride,
command_buffer,
@@ -176,10 +170,10 @@ impl AttentionGemmGroupedMetal {
let head_dim = self.head_dim;
AttnParams {
- q_strides: [self.num_q_heads * suffix_length * head_dim, suffix_length * head_dim, head_dim],
+ 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: [suffix_length * self.num_q_heads * head_dim, head_dim, self.num_q_heads * 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,
@@ -261,15 +255,12 @@ impl AttentionGemmGrouped {
pub fn encode(
&self,
mask: MaskKind,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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;
@@ -294,15 +285,14 @@ impl AttentionGemmGrouped {
gpu_core_count,
);
let gate_applied = core.encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
+ input.queries,
+ input.keys,
+ input.values,
&mut output,
arguments.trie,
arguments.gate,
suffix_length,
kv_length,
- 1,
num_splits,
command_buffer,
)?;
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
index 8ce7dc9a5..58b76a6a8 100644
--- 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
@@ -1,6 +1,9 @@
use super::MaskKind;
use crate::{
- backends::{common::kernel::AttentionKernelConfig, metal::context::MetalContext},
+ backends::{
+ common::{gpu_types::kv_layout, kernel::AttentionKernelConfig},
+ metal::context::MetalContext,
+ },
data_type::DataType,
};
@@ -10,6 +13,8 @@ const GEMM_GROUPED_DECODE_SUFFIX_MAX: u32 = 64;
const GEMM_GROUPED_PREFILL_SUFFIX_MAX: u32 = 1024;
const GEMM_GROUPED_MIN_KV_LENGTH: u32 = 1024;
pub const MAX_TRIE_SUFFIX: u32 = 64;
+const SMALL_SUFFIX_MAX: u32 = 4;
+const SMALL_SUFFIX_MAX_SPLITS: u32 = 16;
pub fn is_supported(
arguments: &AttentionKernelConfig,
@@ -145,6 +150,37 @@ pub fn choose_splits(
splits.clamp(1, max_splits)
}
+pub fn int8_splits(
+ split_rows: u32,
+ head_dim: u32,
+ suffix_length: u32,
+ kv_length: u32,
+) -> u32 {
+ let kv_blocks = kv_length.div_ceil(kv_layout::TILE_KEYS);
+ let splits = if suffix_length <= GEMM_GROUPED_DECODE_SUFFIX_MAX {
+ // Estimate split count using at least 16 query tokens.
+ let query_tokens = suffix_length.max(kv_layout::TILE_QUERIES);
+ let splits = (kv_length as f32 / query_tokens as f32).sqrt().round() as u32;
+ // Tuned on M5 Max.
+ if suffix_length <= SMALL_SUFFIX_MAX {
+ splits.min(SMALL_SUFFIX_MAX_SPLITS)
+ } else {
+ splits
+ }
+ } else if kv_length >= PREFILL_SPLIT_MIN_KV {
+ let row_bytes = head_dim as u64 * DataType::BF16.size_in_bytes() as u64
+ + PARTIAL_STATS_PER_ROW * 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;
+ // Round to the nearest split count.
+ let requested_splits = (kv_length + PREFILL_SPLIT_KEYS / 2) / PREFILL_SPLIT_KEYS;
+ requested_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/gemm_grouped/util.h b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/util.h
new file mode 100644
index 000000000..81777cea1
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/util.h
@@ -0,0 +1,50 @@
+#pragma once
+
+#include <metal_stdlib>
+#include "../../common/defines.h"
+#include "../../common/dsl.h"
+#include "../../matmul/common/mxu_fragment/ops.h"
+
+using namespace metal;
+
+#define ATTENTION_GQA_SIMDGROUPS 8
+
+template <uint BK, uint BD, uint D_SLICES>
+struct AttentionGemmGroupedLayout {
+ using Ops = uzu::matmul::MxuFragmentOps<>;
+
+ UZU_CONST int SIMDGROUPS = ATTENTION_GQA_SIMDGROUPS;
+ UZU_CONST int TILE_ROWS = Ops::FRAGMENT_ROWS;
+ UZU_CONST int SLICE_COLS = int(BD) / int(D_SLICES);
+ UZU_CONST int BANDS = SIMDGROUPS / int(D_SLICES);
+ UZU_CONST int BLOCK_ROWS = BANDS * TILE_ROWS;
+ UZU_CONST int SCORE_TILE_ELEMENTS = TILE_ROWS * int(BK);
+ UZU_CONST int SCORE_EXCHANGE_SIZE = SIMDGROUPS * SCORE_TILE_ELEMENTS;
+};
+
+// `fn(row_in_lane, column, value)` over one lane's elements of `tile`.
+template <class FragmentType, class Fn>
+METAL_FUNC void map_lane_rows(thread FragmentType& tile, const short2 position, Fn fn) {
+ using Ops = typename FragmentType::FragmentOpsType;
+ using Element = typename FragmentType::ElementType;
+ static_assert(FragmentType::ROW_FRAGMENTS == 1, "requires one row fragment");
+ static_assert(
+ Ops::THREAD_ELEMENT_ROWS * Ops::THREAD_ELEMENT_COLS == Ops::ELEMENTS_PER_THREAD,
+ "requires row-major thread elements"
+ );
+
+ thread Element* data = tile.elements();
+ METAL_PRAGMA_UNROLL
+ for (ushort fragment_col = 0; fragment_col < FragmentType::COL_FRAGMENTS; ++fragment_col) {
+ const ushort fragment_base = fragment_col * Ops::ELEMENTS_PER_THREAD;
+ const short col_base = position.x + short(fragment_col) * short(Ops::FRAGMENT_COLS);
+ METAL_PRAGMA_UNROLL
+ for (ushort row = 0; row < Ops::THREAD_ELEMENT_ROWS; ++row) {
+ METAL_PRAGMA_UNROLL
+ for (ushort col = 0; col < Ops::THREAD_ELEMENT_COLS; ++col) {
+ const ushort element = fragment_base + row * Ops::THREAD_ELEMENT_COLS + col;
+ data[element] = Element(fn(row, col_base + short(col), data[element]));
+ }
+ }
+ }
+}
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
new file mode 100644
index 000000000..e3f731421
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/int8/mod.rs
@@ -0,0 +1,171 @@
+use super::gemm_grouped::policy::{MAX_TRIE_SUFFIX, int8_splits};
+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,
+};
+
+const QUERIES_PER_BLOCK: u32 = 2 * kv_layout::TILE_QUERIES;
+
+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 {
+ context.supports_mxu
+ && config.head_dim == 256
+ && config.is_causal
+ && config.data_type == DataType::BF16
+ && !config.has_sinks
+ && config.sliding_window_size.is_none()
+ }
+
+ 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_tiles = grouped_rows.div_ceil(QUERIES_PER_BLOCK);
+ let split_rows = num_groups * query_tiles * QUERIES_PER_BLOCK;
+ 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 * QUERIES_PER_BLOCK,
+ num_groups,
+ num_splits,
+ config.gate_row_stride,
+ command_buffer,
+ );
+ Ok(output)
+ }
+}
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 1530440be..a947192f2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs
@@ -4,6 +4,7 @@ mod error;
mod fallback;
mod gemm;
mod gemm_grouped;
+mod int8;
mod single_pass;
mod two_pass;
@@ -12,7 +13,10 @@ pub use error::AttentionMetalError;
use crate::backends::{
common::{
BufferRef, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernel, AttentionKernelConfig, SigmoidGateKernel},
+ kernel::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, FullPrecisionInput,
+ SigmoidGateKernel,
+ },
},
metal::{Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, kernel::SigmoidGateMetalKernel},
};
@@ -54,6 +58,7 @@ pub struct AttentionMetalKernel {
config: AttentionKernelConfig,
gate: Option<(SigmoidGateMetalKernel, u32)>,
grouped: Option<gemm_grouped::AttentionGemmGrouped>,
+ int8: Option<int8::Int8Attention>,
gemm: Option<gemm::AttentionGemm>,
fallback: Option<fallback::AttentionFallback>,
two_pass: two_pass::AttentionTwoPass,
@@ -70,6 +75,10 @@ impl AttentionKernel for AttentionMetalKernel {
) -> Result<Self, AttentionMetalError> {
let grouped = gemm_grouped::AttentionGemmGrouped::is_supported(&config, context)
.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 fallback = fallback::AttentionFallback::is_supported(&config)
.then(|| fallback::AttentionFallback::new(&config, context))
@@ -82,6 +91,7 @@ impl AttentionKernel for AttentionMetalKernel {
config,
gate,
grouped,
+ int8,
gemm,
fallback,
two_pass: two_pass::AttentionTwoPass::new(&config),
@@ -89,49 +99,61 @@ impl AttentionKernel for AttentionMetalKernel {
})
}
+ fn supports_int8(&self) -> bool {
+ self.int8.is_some()
+ }
+
fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ input: AttentionInput<
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, AttentionMetalError> {
let command_buffer = &mut *command_buffer.debug_group("attention core");
let (gate, suffix_length) = (arguments.gate, arguments.suffix_length);
- self.encode_impl(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
- })
+ 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,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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;
@@ -146,7 +168,7 @@ impl AttentionMetalKernel {
&& let Some(grouped) = &self.grouped
{
if grouped.should_encode(mask, suffix_length, kv_length) {
- return grouped.encode(mask, arguments, command_buffer).map_err(AttentionMetalError::Backend);
+ return grouped.encode(mask, input, arguments, command_buffer).map_err(AttentionMetalError::Backend);
}
// These measured sibling exceptions apply only when the
@@ -155,30 +177,30 @@ impl AttentionMetalKernel {
&& (1..=16).contains(&suffix_length)
&& kv_length > D256_SINGLE_PASS_KV_THRESHOLD
{
- return Ok((self.single_pass.encode(arguments, command_buffer)?, false));
+ return Ok((self.single_pass.encode(input, arguments, command_buffer)?, false));
}
if (self.config.head_dim == 256 && (9..=16).contains(&suffix_length))
|| (self.config.head_dim == 128
&& (9..=16).contains(&suffix_length)
&& kv_length > D128_SHORT_KV_GEMM_THRESHOLD)
{
- return Ok((self.two_pass.encode(arguments, command_buffer)?, gate_applied_by_two_pass));
+ return Ok((self.two_pass.encode(input, arguments, command_buffer)?, gate_applied_by_two_pass));
}
}
if suffix_length > 8 {
if let Some(gemm) = &self.gemm {
- return Ok((gemm.encode(arguments, command_buffer)?, false));
+ return Ok((gemm.encode(input, arguments, command_buffer)?, false));
}
if !is_trie && let Some(fallback) = &self.fallback {
- return Ok((fallback.encode(arguments, command_buffer)?, false));
+ return Ok((fallback.encode(input, arguments, command_buffer)?, false));
}
}
if kv_length > SINGLE_PASS_KV_THRESHOLD {
- Ok((self.two_pass.encode(arguments, command_buffer)?, gate_applied_by_two_pass))
+ Ok((self.two_pass.encode(input, arguments, command_buffer)?, gate_applied_by_two_pass))
} else {
- Ok((self.single_pass.encode(arguments, command_buffer)?, false))
+ Ok((self.single_pass.encode(input, arguments, command_buffer)?, false))
}
}
}
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
index 5e7c8220a..26724143f 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/prepare_int8.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/prepare_int8.metal
@@ -7,20 +7,21 @@
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) {
- constexpr float CODE_MAX = static_cast<float>(metal::numeric_limits<int8_t>::max());
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, CODE_MAX) : 1.0f);
+ 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))), -CODE_MAX, CODE_MAX));
+ int(metal::clamp(metal::rint(metal::precise::divide(values[value_index], float(scale))), -INT8_MAX, INT8_MAX));
}
return scale;
}
@@ -34,10 +35,10 @@ PUBLIC KERNEL(AttentionPrepareInt8)(
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,
- device ElementT* k_scales,
- device uchar* v_codes,
- device ElementT* v_scales,
+ 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,
@@ -45,11 +46,12 @@ PUBLIC KERNEL(AttentionPrepareInt8)(
const constant uint32_t& kv_token_offset,
const constant uint32_t& input_row_stride,
const constant uint32_t& suffix_length,
- const constant uint32_t& padded_suffix,
+ const constant uint32_t& query_rows,
const bool has_rope SPECIALIZE,
const bool quantize_queries SPECIALIZE,
const uint32_t num_kv_heads SPECIALIZE,
- const uint32_t token_idx GROUPS(padded_suffix),
+ 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)
) {
@@ -57,22 +59,15 @@ PUBLIC KERNEL(AttentionPrepareInt8)(
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;
- 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;
-
- if (token_idx >= suffix_length) {
- if (is_query && quantize_queries) {
- const size_t row = size_t(head_idx) * padded_suffix + token_idx;
- METAL_PRAGMA_UNROLL
- for (ushort value_index = 0; value_index < VALUES_PER_LANE; ++value_index) {
- q_codes[row * HEAD_DIM + value_index * METAL_SIMD_SIZE + lane_index] = 0;
- }
- if (lane_index == 0) {
- q_scales[row] = ElementT(1.0f);
- }
- }
+ 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];
@@ -105,7 +100,7 @@ PUBLIC KERNEL(AttentionPrepareInt8)(
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 ? size_t(head_idx) * padded_suffix + token_idx : shape.scale_index(key, kv_head);
+ 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;
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
index c3ce7d9eb..bdfd9c1f8 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs
@@ -2,6 +2,7 @@ use std::collections::{HashMap, hash_map::Entry};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
+use super::FullPrecisionInput;
use crate::backends::{
common::{
Backend, BufferRef, CommandBufferEncoding,
@@ -50,15 +51,12 @@ impl AttentionSinglePass {
pub fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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;
@@ -68,9 +66,9 @@ impl AttentionSinglePass {
)?;
let kernel = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;
kernel.encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
+ input.queries,
+ input.keys,
+ input.values,
&mut output,
config.num_q_heads / config.num_groups,
arguments.cache.prefix_len() + arguments.suffix_length,
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
index 0c9b1a1ee..39d019c07 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs
@@ -2,6 +2,7 @@ use std::collections::{HashMap, hash_map::Entry};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
+use super::FullPrecisionInput;
use crate::{
backends::{
common::{
@@ -76,15 +77,12 @@ impl AttentionTwoPass {
pub fn encode(
&self,
- arguments: AttentionArguments<
- '_,
- Metal,
- impl BufferRef<Backend = Metal>,
- impl BufferRef<Backend = Metal>,
+ 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;
@@ -102,9 +100,9 @@ impl AttentionTwoPass {
)?;
let first = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;
first.encode(
- arguments.queries,
- arguments.keys,
- arguments.values,
+ input.queries,
+ input.keys,
+ input.values,
&mut partials,
&mut sums,
&mut maxs,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/common/conversion.h b/crates/uzu-engine/src/backends/metal/kernel/common/conversion.h
new file mode 100644
index 000000000..61d0b7a7e
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/common/conversion.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include <metal_stdlib>
+
+#include "defines.h"
+
+namespace uzu {
+
+UZU_CONST float FLOAT_OFFSET = 0x1p23f;
+
+// Round [0, 255] to nearest-even without a numeric conversion.
+METAL_FUNC uchar round_to_byte(const float x) { return uchar(as_type<uint>(x + 0x1.8p23f)); }
+
+// Returns float(i) + FLOAT_OFFSET for 0 <= i < 2^23; callers must remove the offset.
+METAL_FUNC float float_with_offset(const uint i) { return as_type<float>(i | as_type<uint>(FLOAT_OFFSET)); }
+
+// Widen two packed BF16 values, low half first.
+METAL_FUNC float2 unpack_bfloat(const uint packed) {
+ return as_type<float2>(uint2(packed << 16, packed & 0xffff0000u));
+}
+
+METAL_FUNC float4 bfloat_to_float(const bfloat4 value) { return as_type<float4>(uint4(as_type<ushort4>(value)) << 16); }
+
+} // namespace uzu
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 de5139242..771093a27 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
@@ -7,6 +7,8 @@ using namespace metal;
namespace uzu::kv_layout {
static constant constexpr uint32_t TILE_KEYS = 32;
+static constant constexpr uint32_t TILE_QUERIES = 16;
+
static constant constexpr uint32_t TILE_DIMS = 16;
static constant constexpr uint32_t FRAGMENT_BYTES = TILE_KEYS * TILE_DIMS;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
index 2647fa395..2bf74883f 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
@@ -166,6 +166,31 @@ struct Fragment {
});
}
+ // Indices address each lane's rows and columns.
+ template <class Fn, class... Fragments>
+ METAL_FUNC void for_each_lane(Fn fn, thread Fragments&... fragments) thread {
+ static_assert(
+ ((Fragments::ROW_FRAGMENTS == ROW_FRAGMENTS && Fragments::COL_FRAGMENTS == COL_FRAGMENTS &&
+ metal::is_same_v<typename Fragments::FragmentOpsType, Ops>) &&
+ ...),
+ "zipped fragments must share this fragment's layout"
+ );
+ static_assert(Ops::THREAD_ELEMENT_ROWS * Ops::THREAD_ELEMENT_COLS == Ops::ELEMENTS_PER_THREAD);
+ METAL_PRAGMA_UNROLL
+ for (ushort tr = 0; tr < ROW_FRAGMENTS; ++tr) {
+ METAL_PRAGMA_UNROLL
+ for (ushort tc = 0; tc < COL_FRAGMENTS; ++tc) {
+ METAL_PRAGMA_UNROLL
+ for (ushort e = 0; e < Ops::ELEMENTS_PER_THREAD; ++e) {
+ const ushort row = tr * Ops::THREAD_ELEMENT_ROWS + e / Ops::THREAD_ELEMENT_COLS;
+ const ushort col = tc * Ops::THREAD_ELEMENT_COLS + e % Ops::THREAD_ELEMENT_COLS;
+ const ushort index = (tr * COL_FRAGMENTS + tc) * Ops::ELEMENTS_PER_THREAD + e;
+ fn(row, col, elements()[index], fragments.elements()[index]...);
+ }
+ }
+ }
+ }
+
// Row lanes differ in bits {0,3} for both simdgroup and MXU layouts.
template <typename Acc, class Fn>
METAL_FUNC void row_reduce(thread Acc* out, const Acc identity, Fn op) thread {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
index e6bab1f36..dc05c6fcf 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
@@ -1,6 +1,7 @@
#pragma once
#include "../../common/quant_unpack.h"
+#include "../../../common/conversion.h"
namespace uzu {
namespace gemm {
@@ -8,17 +9,11 @@ namespace gemm {
template <uint BITS>
struct QuantChunk {
UZU_CONST uint VALUES = 8;
- UZU_CONST uint FLOAT_MANTISSA_BITS = 23;
- UZU_CONST uint FLOAT_EXPONENT_BIAS = 127;
- UZU_CONST uint MANTISSA_BASE_BITS = (FLOAT_EXPONENT_BIAS + FLOAT_MANTISSA_BITS) << FLOAT_MANTISSA_BITS;
- UZU_CONST float MANTISSA_BASE = float(1u << FLOAT_MANTISSA_BITS);
UZU_CONST uint BITS_PER_BYTE = 8;
UZU_CONST uint WORD_BITS = 32;
UZU_CONST uint WORD_LANES = 4;
UZU_CONST uint WORD_BYTES = WORD_BITS / BITS_PER_BYTE;
UZU_CONST uint VECTOR_BYTES = WORD_BYTES * WORD_LANES;
- UZU_CONST uint BF16_BITS = 16;
- UZU_CONST uint BF16_VALUES_PER_WORD = WORD_BITS / BF16_BITS;
template <uint WORDS>
static METAL_FUNC void decode(
@@ -73,7 +68,7 @@ private:
word0 ^= signed_codes ? W4_SIGN_MASK : 0u;
METAL_PRAGMA_UNROLL
for (uint i = 0; i < VALUES; i++) {
- values[i] = as_type<float>(extract_bits(word0, BITS * i, BITS) | MANTISSA_BASE_BITS) - origin;
+ values[i] = float_with_offset(extract_bits(word0, BITS * i, BITS)) - origin;
}
} else {
const uint mask = signed_codes ? W8_SIGN_MASK : 0u;
@@ -81,8 +76,8 @@ private:
word1 ^= mask;
METAL_PRAGMA_UNROLL
for (uint i = 0; i < CODES_PER_WORD; i++) {
- values[i] = as_type<float>(extract_bits(word0, BITS * i, BITS) | MANTISSA_BASE_BITS) - origin;
- values[CODES_PER_WORD + i] = as_type<float>(extract_bits(word1, BITS * i, BITS) | MANTISSA_BASE_BITS) - origin;
+ values[i] = float_with_offset(extract_bits(word0, BITS * i, BITS)) - origin;
+ values[CODES_PER_WORD + i] = float_with_offset(extract_bits(word1, BITS * i, BITS)) - origin;
}
}
}
@@ -90,12 +85,12 @@ private:
template <bool BOUNDED, bool EXPANDS_BF16, typename AT>
static METAL_FUNC void load_values(const device AT* source, thread float (&values)[VALUES], uint valid) {
if constexpr (!BOUNDED && EXPANDS_BF16) {
- constexpr uint BF16_UPPER_BITS = 0xffff0000u;
const uint4 packed = *reinterpret_cast<const device uint4*>(source);
METAL_PRAGMA_UNROLL
for (uint i = 0; i < WORD_LANES; i++) {
- values[BF16_VALUES_PER_WORD * i] = as_type<float>(packed[i] << BF16_BITS);
- values[BF16_VALUES_PER_WORD * i + 1] = as_type<float>(packed[i] & BF16_UPPER_BITS);
+ const float2 widened = unpack_bfloat(packed[i]);
+ values[2 * i] = widened.x;
+ values[2 * i + 1] = widened.y;
}
} else {
METAL_PRAGMA_UNROLL
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
index 6ae4f69bd..1ab90e076 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
@@ -38,15 +38,14 @@ public:
row * params.zero_point_output_stride + group_index * params.zero_point_group_stride;
const uint zero_point_row = zero_point_index / ZERO_POINTS_PER_BYTE;
const uint packed_index = zero_point_index % ZERO_POINTS_PER_BYTE;
- origin[R] = QuantChunk<BITS>::MANTISSA_BASE +
- float(decode_zero_point<BITS>(ops.zero_points + zero_point_row, packed_index));
+ origin[R] = FLOAT_OFFSET + float(decode_zero_point<BITS>(ops.zero_points + zero_point_row, packed_index));
bias[R] = 0.0f;
} else if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleSymmetricDequant) {
- origin[R] = QuantChunk<BITS>::MANTISSA_BASE + float(symmetric_zero_point<BITS>());
+ origin[R] = FLOAT_OFFSET + float(symmetric_zero_point<BITS>());
bias[R] = 0.0f;
} else {
static_assert(B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant);
- origin[R] = QuantChunk<BITS>::MANTISSA_BASE;
+ origin[R] = FLOAT_OFFSET;
bias[R] = float(ops.biases[scale_index]);
}
});
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
new file mode 100644
index 000000000..6929d4de2
--- /dev/null
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
@@ -0,0 +1,129 @@
+use std::any::Any;
+
+use crate::{
+ backends::common::{
+ Backend, Buffer, CommandBuffer, Context, DeviceCapabilities, 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 Buffer<Backend = B>>,
+ pub values: Box<dyn Buffer<Backend = B>>,
+ pub element_dim: u32,
+ pub data_type: DataType,
+}
+
+pub struct Int8KV<B: Backend> {
+ pub layout: Int8KVLayout,
+ pub k_codes: Box<dyn Buffer<Backend = B>>,
+ pub v_codes: Box<dyn Buffer<Backend = B>>,
+ pub k_scales: Box<dyn Buffer<Backend = B>>,
+ pub v_scales: Box<dyn Buffer<Backend = B>>,
+}
+
+fn create_kv_buffer<B: Backend>(
+ context: &B::Context,
+ bytes: usize,
+) -> Result<Box<dyn Buffer<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(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 Buffer<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 d076b308a..a2832494a 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
@@ -4,7 +4,7 @@ use thiserror::Error;
use crate::{
backends::common::{
Backend, CommandBuffer, CommandBufferEncoding, Kernels,
- kernel::{AttentionKernel, AttentionKernelConfig, AttentionPrepareKernel},
+ kernel::{AttentionKernel, AttentionKernelConfig, AttentionPrepareInt8Kernel, AttentionPrepareKernel},
},
config::{rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},
data_type::DataType,
@@ -24,6 +24,7 @@ use crate::{
utils::maybe_mut::MaybeMut,
};
+pub mod kv_storage;
mod mode;
mod qkv_norm;
mod state;
@@ -35,6 +36,7 @@ pub mod rope;
pub struct Attention<B: Backend> {
head_dim: u32,
num_q_heads: u32,
+ num_groups: u32,
num_kv_heads: Option<u32>,
ring_capacity: Option<u32>,
max_rope_length: Option<u32>,
@@ -43,6 +45,7 @@ pub struct Attention<B: Backend> {
projection_dim: u32,
projection: LinearProjection<B>,
prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,
+ prepare_int8: Option<<B::Kernels as Kernels>::AttentionPrepareInt8Kernel>,
sinks: Option<B::GlobalBuffer>,
kernel: <B::Kernels as Kernels>::AttentionKernel,
out_projection: Box<dyn Linear<B>>,
@@ -163,6 +166,22 @@ 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 out_projection = <dyn Linear<B>>::new(
q_dim,
@@ -177,6 +196,7 @@ impl<B: Backend> Attention<B> {
Self {
head_dim,
num_q_heads,
+ num_groups,
num_kv_heads,
ring_capacity,
max_rope_length,
@@ -188,6 +208,7 @@ impl<B: Backend> Attention<B> {
norm: qkv_norm,
},
prepare,
+ prepare_int8,
sinks,
kernel,
out_projection,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
index 881b08334..41de8bca4 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
@@ -1,15 +1,22 @@
use crate::{
backends::common::{
- Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,
- kernel::{AttentionArguments, AttentionKernel, AttentionPrepareKernel},
+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,
+ kernel::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareInt8Kernel, AttentionPrepareKernel,
+ FullPrecisionInput, Int8Input,
+ },
},
+ data_type::DataType,
encodable_block::{
batch_topology::BatchTopology,
linear::Linear,
mixer::{
MixerState,
attention::{
- Attention, AttentionEncodeError, KVCacheView, qkv_norm::QKVNorm, rope::PrecalculatedRoPE,
+ Attention, AttentionEncodeError, KVCacheView,
+ kv_storage::{Int8KV, KVStorage},
+ qkv_norm::QKVNorm,
+ rope::PrecalculatedRoPE,
state::AttentionState,
},
},
@@ -17,6 +24,14 @@ use crate::{
utils::maybe_mut::MaybeMut,
};
+enum KVBuffers<'a, B: Backend> {
+ BF16 {
+ keys: MaybeMut<'a, dyn Buffer<Backend = B>>,
+ values: MaybeMut<'a, dyn Buffer<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>,
@@ -51,79 +66,116 @@ impl<B: Backend> Attention<B> {
)
});
- let attention_output = match state {
- Some(MaybeMut::Mut(state)) => {
- let prefix_len = state.view().prefix_len();
- let queries = self
- .prepare_kv_and_queries(
- &qkvg,
- state.keys.as_mut(),
- state.values.as_mut(),
- prefix_len,
- self.num_q_heads,
- precalculated_rope,
- batch_dim.size(),
- command_buffer,
- )
- .map_err(AttentionEncodeError::Backend)?;
- self.run_core(&queries, gate, batch_dim, state, command_buffer)?
- },
- Some(MaybeMut::Const(state)) => {
- // KV sharing: QKVG contains queries and an optional gate only.
- let queries = self
- .prepare_queries(&qkvg, precalculated_rope, batch_dim.size(), command_buffer)
- .map_err(AttentionEncodeError::Backend)?;
- self.run_core(&queries, gate, batch_dim, state, command_buffer)?
- },
- 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");
-
- let mut keys = command_buffer
- .allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)
- .map_err(AttentionEncodeError::Backend)?;
- let mut values = command_buffer
- .allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)
- .map_err(AttentionEncodeError::Backend)?;
-
- let queries = self
- .prepare_kv_and_queries(
- &qkvg,
- &mut keys,
- &mut values,
- 0,
- self.num_q_heads,
- precalculated_rope,
- batch_dim.size(),
- command_buffer,
- )
- .map_err(AttentionEncodeError::Backend)?;
-
- let cache = self.ring_capacity.map_or_else(|| KVCacheView::full(0), |_| KVCacheView::ring(0, 0));
-
- self.kernel
- .encode(
- AttentionArguments {
- queries: &queries,
- keys: &keys,
- values: &values,
- suffix_length: batch_dim.size(),
- trie: None::<&B::ConstantBuffer>,
- sinks: self.sinks.as_ref(),
- cache,
- gate,
+ 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()),
},
- command_buffer,
- )
- .map_err(AttentionEncodeError::Kernel)?
- },
+ 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)?
};
- self.out_projection
- .encode(attention_output, batch_dim.size(), command_buffer)
- .map_err(AttentionEncodeError::Linear)
+ Ok(self.out_projection.encode(attention_output, batch_dim.size(), command_buffer)?)
}
pub fn append_projected_kv(
@@ -136,122 +188,125 @@ impl<B: Backend> Attention<B> {
) -> Result<(), B::Error> {
self.projection.norm.encode_key_value(key_value.reborrow(), batch_dim, command_buffer);
let prefix_len = state.view().prefix_len();
- self.prepare_kv_and_queries(
- key_value.as_ref(),
- state.keys.as_mut(),
- state.values.as_mut(),
- prefix_len,
- 0,
- Some(precalculated_rope),
- batch_dim,
- command_buffer,
- )?;
+ 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 run_core(
+ fn prepare_bf16(
&self,
- queries: impl BufferRef<Backend = B>,
- gate: Option<impl BufferRef<Backend = B>>,
- batch_dim: &BatchTopology,
- state: &AttentionState<B>,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, AttentionEncodeError<B>> {
- let trie = if batch_dim.is_flat() {
- None
- } else {
- Some(
- command_buffer
- .allocate_constant_from_slice(batch_dim.nodes())
- .map_err(AttentionEncodeError::Backend)?,
- )
- };
-
- self.kernel
- .encode(
- AttentionArguments {
- queries,
- keys: state.keys.as_ref(),
- values: state.values.as_ref(),
- suffix_length: batch_dim.size(),
- trie: trie.as_ref(),
- sinks: self.sinks.as_ref(),
- cache: state.view(),
- gate,
- },
- command_buffer,
- )
- .map_err(AttentionEncodeError::Kernel)
- }
-
- fn prepare_kv_and_queries(
- &self,
- input: impl BufferRef<Backend = B>,
- keys: impl BufferMut<Backend = B>,
- values: impl BufferMut<Backend = B>,
+ qkvg: impl BufferRef<Backend = B>,
+ keys: &mut MaybeMut<'_, dyn Buffer<Backend = B>>,
+ values: &mut MaybeMut<'_, dyn Buffer<Backend = B>>,
kv_token_offset: u32,
num_q_heads: u32,
- precalculated_rope: Option<&PrecalculatedRoPE<B>>,
- batch_dim: u32,
+ rope: Option<&PrecalculatedRoPE<B>>,
+ suffix_length: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<B::ScratchBuffer, B::Error> {
- let num_kv_heads = self.num_kv_heads.expect("KV prepare requires KV heads");
- // Appended KV is tightly packed; attention projections may have a trailing gate segment.
+ 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 * num_kv_heads * self.head_dim
+ 2 * self.num_groups * self.head_dim
} else {
self.projection_dim
};
- let mut queries = if num_q_heads == 0 {
- command_buffer.allocate_scratch(self.data_type.size_in_bytes())?
- } else {
- command_buffer.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?
- };
+ 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(
- input,
+ qkvg,
&mut queries,
- Some(keys),
- Some(values),
- precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),
- precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),
+ output_keys,
+ output_values,
+ rope.map(|rope| &rope.cosines),
+ rope.map(|rope| &rope.sines),
num_q_heads,
- Some(num_kv_heads),
+ append_kv.then_some(self.num_groups),
self.head_dim,
- precalculated_rope.map(|precalculated_rope| precalculated_rope.dim),
- Some(kv_token_offset),
+ rope.map(|rope| rope.dim),
+ append_kv.then_some(kv_token_offset),
input_row_stride,
- batch_dim,
+ suffix_length,
command_buffer,
);
Ok(queries)
}
- fn prepare_queries(
+ fn prepare_int8(
&self,
qkvg: impl BufferRef<Backend = B>,
- precalculated_rope: Option<&PrecalculatedRoPE<B>>,
- batch_dim: u32,
+ 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::Error> {
- let mut queries =
- command_buffer.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?;
- self.prepare.encode(
+ ) -> 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,
- &mut queries,
None::<&mut B::ScratchBuffer>,
- None::<&mut B::ScratchBuffer>,
- precalculated_rope.map(|rope| &rope.cosines),
- precalculated_rope.map(|rope| &rope.sines),
- self.num_q_heads,
- None,
- self.head_dim,
- precalculated_rope.map(|rope| rope.dim),
- None,
- self.projection_dim,
- batch_dim,
+ 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(queries)
+ Ok((query_codes, query_scales))
}
}
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 dddbacb68..31e4b23fa 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
@@ -1,14 +1,13 @@
-use std::any::Any;
-
use crate::{
backends::common::{
- Backend, Buffer, CommandBuffer, Context, DeviceCapabilities, Kernels, SparseBuffer,
+ Backend, CommandBuffer,
gpu_types::{kv_cache_update::Copy, ring::RingParams},
- kernel::KVCacheUpdateKernel,
+ kernel::{AttentionKernel, KVFormat},
+ },
+ encodable_block::mixer::{
+ MixerState,
+ attention::{Attention, kv_storage::KVStorage},
},
- data_type::DataType,
- encodable_block::mixer::{MixerState, attention::Attention},
- utils::size_for_shape::size_for_shape,
};
pub const ATTENTION_SUFFIX_CAPACITY: u32 = 1024; // TODO: remove hardcoded suffix capacity
@@ -161,13 +160,8 @@ impl KVCacheState {
}
pub struct AttentionState<B: Backend> {
- pub element_dim: u32,
- pub data_type: DataType,
cache: KVCacheState,
- pub is_sparse: bool,
- pub keys: Box<dyn Buffer<Backend = B>>,
- pub values: Box<dyn Buffer<Backend = B>>,
- pub kv_cache_update: <B::Kernels as Kernels>::KVCacheUpdateKernel,
+ pub kv: KVStorage<B>,
}
impl<B: Backend> AttentionState<B> {
@@ -187,8 +181,6 @@ impl<B: Backend> AttentionState<B> {
);
}
- let data_type = attention.data_type;
-
let max_prefix_elements = attention.ring_capacity.unwrap_or_else(|| {
max_context_length
.or(attention.max_rope_length)
@@ -197,31 +189,23 @@ impl<B: Backend> AttentionState<B> {
let cache = attention.ring_capacity.map_or_else(KVCacheState::full, KVCacheState::ring);
- let max_elements = max_prefix_elements + ATTENTION_SUFFIX_CAPACITY;
- let element_dim = attention.num_kv_heads.unwrap() * attention.head_dim;
- let kv_buffer_bytes = size_for_shape(&[max_elements, element_dim], data_type);
-
- let is_sparse = context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS);
-
- let (keys, values): (Box<dyn Buffer<Backend = B>>, Box<dyn Buffer<Backend = B>>) = if is_sparse {
- (
- Box::new(context.create_sparse_buffer(kv_buffer_bytes)?),
- Box::new(context.create_sparse_buffer(kv_buffer_bytes)?),
- )
+ let format = if attention.kernel.supports_int8() {
+ KVFormat::INT8
} else {
- (Box::new(context.create_buffer(kv_buffer_bytes)?), Box::new(context.create_buffer(kv_buffer_bytes)?))
+ KVFormat::BF16
};
-
- let kv_cache_update = <B::Kernels as Kernels>::KVCacheUpdateKernel::new(context, data_type)?;
+ let kv = KVStorage::create_empty(
+ format,
+ attention.num_kv_heads.unwrap(),
+ attention.head_dim,
+ max_prefix_elements + ATTENTION_SUFFIX_CAPACITY,
+ attention.data_type,
+ context,
+ )?;
Ok(Self {
- element_dim,
- data_type,
cache,
- is_sparse,
- keys,
- values,
- kv_cache_update,
+ kv,
})
}
}
@@ -234,18 +218,7 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {
) -> Result<(), B::Error> {
assert!(suffix_length <= ATTENTION_SUFFIX_CAPACITY, "suffix exceeds capacity");
- if self.is_sparse {
- let elements_required = self.cache.required_prefix_len(context_length) + suffix_length;
- let bytes_required = size_for_shape(&[elements_required, self.element_dim], self.data_type);
-
- let keys = (self.keys.as_mut() as &mut dyn Any).downcast_mut::<B::SparseBuffer>().unwrap();
- let values = (self.values.as_mut() as &mut dyn Any).downcast_mut::<B::SparseBuffer>().unwrap();
-
- keys.map(bytes_required)?;
- values.map(bytes_required)?;
- }
-
- Ok(())
+ self.kv.prepare(self.cache.required_prefix_len(context_length) + suffix_length)
}
fn encode_accept(
@@ -256,14 +229,7 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {
let copies = self.cache.accept(accepted_indices);
if !copies.is_empty() {
- self.kv_cache_update.encode(
- self.keys.as_mut(),
- self.values.as_mut(),
- &copies,
- copies.len() as u32,
- self.element_dim,
- command_buffer,
- );
+ self.kv.encode_accept(&copies, command_buffer);
}
Ok(())
diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rs
index 4517ed87f..f20a044db 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -8,8 +8,8 @@ use crate::{
CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FrontierIdx, MetadataIdx, TreeIdx,
},
kernel::{
- AncestorAttentionKernel, AttentionArguments, AttentionKernel, WeaverFrontierSelectKernel,
- WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,
+ AncestorAttentionKernel, AttentionArguments, AttentionInput, AttentionKernel, FullPrecisionInput,
+ WeaverFrontierSelectKernel, WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,
},
},
config::{rope::AnyRoPEConfig, weaver::WeaverConfig},
@@ -334,10 +334,12 @@ impl<B: Backend> Weaver<B> {
let attention_output = layer
.prefix_attention
.encode(
- AttentionArguments {
+ AttentionInput::FullPrecision(FullPrecisionInput {
queries: &queries,
keys: &kv_cache,
values: kv_cache.subrange(kv_plane_bytes..),
+ }),
+ AttentionArguments {
suffix_length: depth,
trie: None::<&B::ConstantBuffer>,
sinks: None,
@@ -433,11 +435,11 @@ impl<B: Backend> Weaver<B> {
let node_metadata = node_metadata.as_ref();
let metadata_field_bytes = size_for_shape(&[batch_node_count], DataType::U32);
for layer in &self.layers {
- let attention_input = layer
+ let input = layer
.pre_attention_norm
.encode(&residual_input, 0, batch_node_count, Some(&mut residual_state), command_buffer)
.map_err(WeaverEncodeError::Backend)?;
- let current_qkv = layer.qkv_projection.encode(attention_input, batch_node_count, command_buffer)?;
+ let current_qkv = layer.qkv_projection.encode(input, batch_node_count, command_buffer)?;
let mut attention_output = command_buffer
.allocate_scratch_for_shape(&[batch_node_count, self.model_dim], DATA_TYPE)
.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 161bc17b8..a94ad393a 100644
--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
@@ -153,11 +153,11 @@ impl<B: Backend> WeaverLayer<B> {
token_count: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<PreparedPrefixAttention<B>, WeaverEncodeError<B>> {
- let attention_input = self
+ let input = self
.pre_attention_norm
.encode(residual_input, 0, token_count, Some(residual_state), command_buffer)
.map_err(WeaverEncodeError::Backend)?;
- let qkv = self.qkv_projection.encode(attention_input, token_count, command_buffer)?;
+ 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)
.map_err(WeaverEncodeError::Backend)?;
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 d213fc357..cbc2ffd04 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
@@ -138,15 +138,15 @@ struct Int8Output {
scales: [Vec<bf16>; 3],
}
-fn run_int8<B: Backend>() -> Int8Output {
+fn run_int8<B: Backend>(num_q_heads: u32) -> Int8Output {
const DIM: usize = 256;
const CACHE_TOKENS: usize = 64;
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 context = B::Context::new().unwrap();
- let qkvg = create_buffer_with_data::<B, bf16>(&context, &rows);
- let mut q_codes = create_buffer::<B, i8>(&context, DIM);
- let mut q_scales = create_buffer::<B, bf16>(&context, 1);
+ 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 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]);
@@ -159,6 +159,7 @@ fn run_int8<B: Backend>() -> Int8Output {
false,
true,
1,
+ true,
)
.unwrap();
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
@@ -167,18 +168,18 @@ fn run_int8<B: Backend>() -> Int8Output {
None::<&mut B::GlobalBuffer>,
Some(&mut q_codes),
Some(&mut q_scales),
- &mut k_codes,
- &mut k_scales,
- &mut v_codes,
- &mut v_scales,
+ Some(&mut k_codes),
+ Some(&mut k_scales),
+ Some(&mut v_codes),
+ Some(&mut v_scales),
None::<&B::GlobalBuffer>,
None::<&B::GlobalBuffer>,
- 1,
+ num_q_heads,
None,
33,
- (3 * DIM) as u32,
- 1,
+ (num_q_heads + 2) * DIM as u32,
1,
+ num_q_heads,
&mut command_buffer,
);
command_buffer.end_encoding().submit().wait_until_completed().unwrap();
@@ -191,8 +192,10 @@ fn run_int8<B: Backend>() -> Int8Output {
#[uzu_test]
fn test_attention_prepare_int8() {
- let cpu = run_int8::<Cpu>();
- for_each_non_cpu_backend!(|B| {
- assert_eq!(cpu, run_int8::<B>(), "INT8 prepare mismatch on {}", std::any::type_name::<B>());
- });
+ 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>());
+ });
+ }
}
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
index c486acfdc..1ca7955e6 100644
--- 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
@@ -1,6 +1,6 @@
use uzu_engine_macros::uzu_test;
-use super::{MaskKind, SplitGeometry, choose_splits, should_encode};
+use super::{MaskKind, SplitGeometry, choose_splits, int8_splits, should_encode};
fn geometry(head_dim: u32) -> SplitGeometry {
let (num_q_heads, block_rows, num_groups) = if head_dim == 128 {
@@ -83,3 +83,12 @@ fn long_prefill_split_selection_boundaries() {
};
assert_eq!(choose_splits(many_heads, 1024, 61_440, 40), 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
index b184ea37d..e04412465 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
@@ -4,11 +4,12 @@ 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, AttentionKernel, AttentionKernelConfig},
+ kernel::{AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig},
},
cpu::Cpu,
metal::Metal,
@@ -79,21 +80,23 @@ fn get_test_data<T: DataTypeRepr + Float>(
(input, expected)
}
-fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
+fn get_output<T: DataTypeRepr + Float, B: Backend>(fixture: &Input<T>) -> Vec<T> {
let context = B::Context::new().expect("Failed to create Context");
- let config = attention_config(input);
+ let config = attention_config(fixture);
- let queries_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.queries);
- let keys_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.keys);
- let values_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.values);
+ 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 = input.sequence_length - input.suffix_length;
- let args = AttentionArguments {
+ let segment_prefix_length = fixture.sequence_length - fixture.suffix_length;
+ let input = AttentionInput::FullPrecision(FullPrecisionInput {
queries: &queries_buffer,
keys: &keys_buffer,
values: &values_buffer,
- suffix_length: input.suffix_length as u32,
+ });
+ let args = AttentionArguments {
+ suffix_length: fixture.suffix_length as u32,
trie: None::<&B::GlobalBuffer>,
sinks: None,
cache: KVCacheView::full(segment_prefix_length as u32),
@@ -103,9 +106,9 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
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(args, &mut command_buffer).expect("Failed to encode attention");
+ 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(), input.suffix_length * input.num_heads * input.head_dim);
+ 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);
let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();
@@ -124,10 +127,12 @@ fn get_gemm_output<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
let pooled = super::gemm::AttentionGemm::new(&config)
.encode(
- AttentionArguments {
+ FullPrecisionInput {
queries: &queries,
keys: &keys,
values: &values,
+ },
+ AttentionArguments {
suffix_length: input.suffix_length as u32,
trie: None::<&<Metal as Backend>::GlobalBuffer>,
sinks: None,
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 7684edc83..627a1efdd 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
@@ -1,19 +1,25 @@
use half::bf16;
use uzu_engine_macros::uzu_test;
-use super::{gemm, single_pass, two_pass};
+use super::super::FullPrecisionInput;
use crate::{
backends::{
common::{
- Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
+ Backend, BufferRef, CommandBufferEncoding, Context, Kernels,
gpu_types::trie::TrieNode as GpuTrieNode,
- kernel::{AttentionArguments, AttentionKernel, SigmoidGateKernel},
+ kernel::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareInt8Kernel, Int8Input, KVFormat,
+ SigmoidGateKernel,
+ },
},
cpu::Cpu,
metal::Metal,
},
- data_type::DataTypeRepr,
- encodable_block::{mixer::attention::KVCacheView, sampling::PRng},
+ data_type::{DataType, DataTypeRepr},
+ encodable_block::{
+ mixer::attention::{KVCacheView, kv_storage::KVStorage},
+ sampling::PRng,
+ },
tests::{
assert::assert_eq_float,
helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, submit_command_buffer},
@@ -44,8 +50,7 @@ fn run_attention<B: Backend>(
sinks_data: Option<&[bf16]>,
) -> Vec<bf16> {
let (keys, values) = attention_data(shape);
- let (_, _, _, _, prefix_length, _) = shape;
- let (head_dim, num_q_heads, num_groups, _, _, is_causal) = 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");
@@ -77,14 +82,13 @@ fn run_attention_with_kernel<B: Backend>(
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| {
- let words: Vec<u32> = nodes.iter().flat_map(|node| [node.trie_start, node.trie_end, node.height]).collect();
- create_buffer_with_data::<B, u32>(context, &words)
- });
- let arguments = AttentionArguments {
+ 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(),
@@ -92,79 +96,11 @@ fn run_attention_with_kernel<B: Backend>(
gate: None::<&B::GlobalBuffer>,
};
let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");
- let pooled = kernel.encode(arguments, &mut command_buffer).expect("encode");
+ 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);
- let completed = command_buffer.end_encoding().submit().wait_until_completed().expect("submit");
- drop(pooled);
- drop(completed);
- buffer_to_vec::<B, bf16>(&output)
-}
-
-enum DirectKernel {
- SinglePass,
- TwoPass,
- Gemm,
-}
-
-fn run_direct_metal(
- context: &<Metal as Backend>::Context,
- shape: AttentionShape,
- sinks_data: Option<&[bf16]>,
- route: DirectKernel,
-) -> Vec<bf16> {
- let (head_dim, num_q_heads, num_groups, suffix_length, 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 (keys_data, values_data) = attention_data(shape);
- let queries =
- create_buffer_with_data::<Metal, bf16>(context, &fill_attention(num_q_heads * suffix_length * head_dim, 0.5));
- let keys = create_buffer_with_data::<Metal, bf16>(context, &keys_data);
- let values = create_buffer_with_data::<Metal, bf16>(context, &values_data);
- let sinks = sinks_data.map(|data| create_buffer_with_data::<Metal, bf16>(context, data));
- let arguments = AttentionArguments {
- queries: &queries,
- keys: &keys,
- values: &values,
- suffix_length: suffix_length as u32,
- trie: None::<&<Metal as Backend>::GlobalBuffer>,
- sinks: sinks.as_ref(),
- cache: KVCacheView::full(prefix_length as u32),
- gate: None::<&<Metal as Backend>::GlobalBuffer>,
- };
- let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");
- let pooled = match route {
- DirectKernel::SinglePass => {
- single_pass::AttentionSinglePass::new(&config).encode(arguments, &mut command_buffer)
- },
- DirectKernel::TwoPass => two_pass::AttentionTwoPass::new(&config).encode(arguments, &mut command_buffer),
- DirectKernel::Gemm => gemm::AttentionGemm::new(&config).encode(arguments, &mut command_buffer),
- }
- .expect("direct attention");
- let mut output = create_buffer::<Metal, bf16>(context, suffix_length * num_q_heads * head_dim);
- command_buffer.encode_copy(&pooled, &mut output);
submit_command_buffer(command_buffer);
- buffer_to_vec::<Metal, bf16>(&output)
-}
-
-#[uzu_test]
-fn direct_bf16_attention_matches_cpu() {
- let cpu = <Cpu as Backend>::Context::new().expect("CPU context");
- let metal = <Metal as Backend>::Context::new().expect("Metal context");
- for (shape, route, has_sinks) in [
- ((64, 4, 4, 8, 0, false), DirectKernel::SinglePass, false),
- ((64, 4, 4, 64, 0, false), DirectKernel::SinglePass, true),
- ((64, 8, 2, 8, 0, false), DirectKernel::SinglePass, false),
- ((64, 8, 2, 256, 0, true), DirectKernel::SinglePass, false),
- ((64, 8, 2, 256, 0, true), DirectKernel::Gemm, false),
- ((64, 8, 8, 128, 0, false), DirectKernel::TwoPass, false),
- ((64, 8, 2, 64, 1024, false), DirectKernel::TwoPass, false),
- ] {
- let sinks = has_sinks.then(|| vec![bf16::from_f32(1.0); shape.1]);
- let expected = run_attention::<Cpu>(cpu.as_ref(), shape, None, sinks.as_deref());
- let actual = run_direct_metal(metal.as_ref(), shape, sinks.as_deref(), route);
- assert_eq_float::<bf16>(&expected, &actual, 1e-2, "direct BF16 attention");
- }
+ buffer_to_vec::<B, bf16>(&output)
}
#[uzu_test]
@@ -184,6 +120,10 @@ fn attention_kernel_matches_cpu() {
(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),
] {
let nodes = use_trie.then_some(trie.as_slice());
let shape = (head_dim, num_q_heads, num_groups, suffix_length, prefix_length, causal);
@@ -192,9 +132,8 @@ fn attention_kernel_matches_cpu() {
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);
}
- let sinks = vec![bf16::from_f32(1.0); 8];
- for prefix_length in [32, 2048] {
- let shape = (512, 8, 2, 1, prefix_length, false);
+ 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");
@@ -214,29 +153,12 @@ fn attention_kernel_reuses_instance_for_flat_and_trie() {
.expect("attention kernel");
let (keys, values) = attention_data(shape);
let cache = KVCacheView::full(1024);
- let flat = run_attention_with_kernel::<Metal>(context.as_ref(), &kernel, shape, &keys, &values, cache, None, None);
- let trie_output =
- run_attention_with_kernel::<Metal>(context.as_ref(), &kernel, shape, &keys, &values, cache, Some(&trie), None);
- let cpu_context = <Cpu as Backend>::Context::new().expect("CPU attention context");
- let cpu_kernel = <<Cpu as Backend>::Kernels as Kernels>::AttentionKernel::new(
- cpu_context.as_ref(),
- super::default_attention_config::<bf16>(shape.0, shape.1, shape.2, shape.5),
- )
- .expect("CPU attention kernel");
- let expected_flat =
- run_attention_with_kernel::<Cpu>(cpu_context.as_ref(), &cpu_kernel, shape, &keys, &values, cache, None, None);
- let expected_trie = run_attention_with_kernel::<Cpu>(
- cpu_context.as_ref(),
- &cpu_kernel,
- shape,
- &keys,
- &values,
- cache,
- Some(&trie),
- None,
- );
- assert_eq_float::<bf16>(&expected_flat, &flat, 1e-2, "flat mask specialization");
- assert_eq_float::<bf16>(&expected_trie, &trie_output, 1e-2, "trie mask specialization");
+ let cpu = <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]
@@ -252,57 +174,27 @@ fn attention_kernel_ring_matches_full_on_wrap() {
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;
- for index in 0..CAPACITY {
- let source = CONTEXT - CAPACITY + index;
- let destination = (ring_offset + index) % CAPACITY;
- ring_keys[destination * row..(destination + 1) * row]
- .copy_from_slice(&full_keys[source * row..(source + 1) * row]);
- ring_values[destination * row..(destination + 1) * row]
- .copy_from_slice(&full_values[source * row..(source + 1) * row]);
- }
- for index in 0..SUFFIX {
- let source = CONTEXT + index;
- let destination = CAPACITY + index;
- ring_keys[destination * row..(destination + 1) * row]
- .copy_from_slice(&full_keys[source * row..(source + 1) * row]);
- ring_values[destination * row..(destination + 1) * row]
- .copy_from_slice(&full_values[source * row..(source + 1) * row]);
+ 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]);
+ }
}
let context = <Metal as Backend>::Context::new().expect("Metal attention context");
- let full_kernel = <<Metal as Backend>::Kernels as Kernels>::AttentionKernel::new(context.as_ref(), {
- let mut config = super::default_attention_config::<bf16>(shape.0, shape.1, shape.2, shape.5);
- config.sliding_window_size = Some(CAPACITY as u32);
- config
- })
- .expect("full attention kernel");
- let ring_kernel = <<Metal as Backend>::Kernels as Kernels>::AttentionKernel::new(context.as_ref(), {
- let mut config = super::default_attention_config::<bf16>(shape.0, shape.1, shape.2, shape.5);
- config.is_kv_cache_ring = true;
- config.sliding_window_size = Some(CAPACITY as u32);
- config
- })
- .expect("ring attention kernel");
- let full = run_attention_with_kernel::<Metal>(
- context.as_ref(),
- &full_kernel,
- shape,
- &full_keys,
- &full_values,
- KVCacheView::full(CONTEXT as u32),
- None,
- None,
- );
- let ring = run_attention_with_kernel::<Metal>(
- context.as_ref(),
- &ring_kernel,
- shape,
- &ring_keys,
- &ring_values,
- KVCacheView::ring(CAPACITY as u32, ring_offset as u32),
- None,
- None,
- );
+ 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");
}
@@ -328,10 +220,12 @@ fn check_attention_gate<B: Backend>(
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 arguments = |gate| AttentionArguments {
+ let input = AttentionInput::FullPrecision(FullPrecisionInput {
queries: &queries,
keys: &keys,
values: &values,
+ });
+ let arguments = |gate| AttentionArguments {
suffix_length: suffix_length as u32,
trie: None::<&B::GlobalBuffer>,
sinks: None,
@@ -340,7 +234,7 @@ fn check_attention_gate<B: Backend>(
};
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(arguments(None), &mut command_buffer).expect("plain attention");
+ let mut expected = plain.encode(input, arguments(None), &mut command_buffer).expect("plain attention");
sigmoid_gate.encode(
gate_segment,
&mut expected,
@@ -349,7 +243,7 @@ fn check_attention_gate<B: Backend>(
PROJECTION_DIM as u32,
&mut command_buffer,
);
- let fused = gated.encode(arguments(Some(gate_segment)), &mut command_buffer).expect("gated attention");
+ 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);
@@ -375,3 +269,127 @@ fn attention_gate_matches_standalone_gate_on_metal() {
check_attention_gate::<Metal>(context.as_ref(), suffix_length, prefix_length);
}
}
+
+#[uzu_test]
+fn int8_attention_matches_cpu() {
+ const DIM: usize = 256;
+ const KV_HEADS: usize = 4;
+ let (metal, cpu) = (<Metal as Backend>::Context::new().unwrap(), <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),
+ ] {
+ let (shape, nodes) = ((DIM, q_heads, KV_HEADS, suffix, prefix, true), use_trie.then_some(trie.as_slice()));
+ let config = super::default_attention_config::<bf16>(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) * DIM);
+ let mut rows = vec![bf16::ZERO; (prefix + suffix) * stride];
+ for (row, (k, v)) in rows.chunks_mut(stride).zip(keys.chunks(KV_HEADS * DIM).zip(values.chunks(KV_HEADS * DIM)))
+ {
+ let (key_row, value_row) = row[q_heads * DIM..].split_at_mut(KV_HEADS * DIM);
+ key_row.copy_from_slice(k);
+ value_row.copy_from_slice(v);
+ }
+ for (index, query) in fill_attention(q_heads * suffix * DIM, 0.5).chunks(DIM).enumerate() {
+ rows[(prefix + index % suffix) * stride + index / suffix * DIM..][..DIM].copy_from_slice(query);
+ }
+ let mut cache =
+ KVStorage::<Metal>::create_empty(KVFormat::INT8, KV_HEADS as u32, 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);
+ }
+ 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| {
+ let suffix = rows.len() / stride;
+ let query_rows = q_heads / KV_HEADS * suffix;
+ let prepare = Prepare::new(
+ &metal,
+ DataType::BF16,
+ DataType::F32,
+ 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 * 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>::GlobalBuffer>,
+ 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>::GlobalBuffer>,
+ None::<&<Metal as Backend>::GlobalBuffer>,
+ 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>::GlobalBuffer>,
+ };
+ let pooled = kernel.encode(input, arguments, &mut command_buffer).unwrap();
+ let mut output = create_buffer::<Metal, bf16>(&metal, suffix * q_heads * DIM);
+ command_buffer.encode_copy(&pooled, &mut output);
+ drop((pooled, trie));
+ submit_command_buffer(command_buffer);
+ buffer_to_vec::<Metal, bf16>(&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 * DIM..].fill(bf16::ONE));
+ actual = step(&rows[prefix * stride..], prefix, nodes, false);
+ }
+ 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);
+ }
+}
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 164977a36..2835a85f3 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/mod.rs
@@ -1,6 +1,6 @@
#![cfg(backend = "metal")]
-use super::{gemm, single_pass, two_pass};
+use super::gemm;
use crate::{backends::common::kernel::AttentionKernelConfig, data_type::DataTypeRepr};
mod gemm_test;