A high-performance inference engine for AI models
Generalize attention Q/KV modes (#582)
CCYehadb97643730e
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rsindex d5bf5e75f..9b79ba6a5 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs@@ -50,7 +50,7 @@ pub fn attention_prepare<ElementT: ArrayElement + Float, RopeT: ArrayElement + F#[specialize] has_kv: bool,#[specialize] has_rope: bool,) {- assert!(num_q_heads > 0, "attention prepare requires at least one query head");+ assert!(num_q_heads > 0 || has_kv, "attention prepare without KV requires at least one query head");assert!(head_dim > 0, "attention prepare requires nonzero head_dim");assert_eq!(keys.is_some(), has_kv, "attention prepare keys presence mismatch");assert_eq!(values.is_some(), has_kv, "attention prepare values presence mismatch");diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rsindex b46f83d75..6413c514e 100644--- a/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs@@ -1,10 +1,8 @@use thiserror::Error;use crate::{- array::size_for_shape,backends::common::{Allocation, Backend, Encoder, Kernels,- gpu_types::trie::TrieNode,kernel::{AttentionPrepareKernel, SigmoidGateKernel},},config::{rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},@@ -15,10 +13,11 @@ use crate::{mixer::{Mixer, MixerState,attention::{- core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, AttentionCores},+ core::{AttentionCoreNewArguments, AttentionCores},+ mode::{LinearProjection, QkvProjection},qkv_norm::{QKVNorm, QKVNormError},rope::PrecalculatedRoPE,- state::{AttentionState, AttentionStateType},+ state::AttentionState,},},},@@ -27,6 +26,7 @@ use crate::{};mod core;+mod mode;mod qkv_norm;mod state;@@ -39,12 +39,9 @@ pub struct Attention<B: Backend> {is_causal: bool,sliding_window_size: Option<usize>,max_rope_length: Option<usize>,- is_kv_sharing: bool,data_type: DataType,- qkv_projection: Box<dyn Linear<B>>,+ projection: QkvProjection<B>,gate_projection: Option<Box<dyn Linear<B>>>,- qkv_norm: Option<QKVNorm<B>>,- prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,sinks: Option<Allocation<B>>,flat_core: AttentionCores<B>,trie_core: AttentionCores<B>,@@ -160,19 +157,29 @@ impl<B: Backend> Attention<B> {rope_config.is_some(),).map_err(AttentionNewError::Backend)?;+ let projection = QkvProjection::Packed {+ qkv: LinearProjection {+ lin: qkv_projection,+ norm: qkv_norm,+ },+ prepare,+ };let sinks = config.has_sinks.then(|| parameter_tree.leaf("sinks")?.validate(&[num_q_heads], data_type)?.read_allocation()).transpose()?;+ // TODO: remove when wiring with DFlash: split non-causal attention needs full KV storage and a window mask.+ let is_kv_cache_ring = sliding_window_size.is_some();+let flat_core = AttentionCores::new(AttentionCoreNewArguments {head_dim,num_groups,num_q_heads,has_sinks: sinks.is_some(),- is_kv_cache_ring: sliding_window_size.is_some(),+ is_kv_cache_ring,is_causal,is_trie: false,sliding_window_size,@@ -189,7 +196,7 @@ impl<B: Backend> Attention<B> {num_groups,num_q_heads,has_sinks: sinks.is_some(),- is_kv_cache_ring: sliding_window_size.is_some(),+ is_kv_cache_ring,is_causal,is_trie: true,sliding_window_size,@@ -222,12 +229,9 @@ impl<B: Backend> Attention<B> {is_causal,sliding_window_size,max_rope_length,- is_kv_sharing,data_type,- qkv_projection,+ projection,gate_projection,- qkv_norm,- prepare,sinks,flat_core,trie_core,@@ -268,137 +272,6 @@ impl<B: Backend> Mixer<B> for Attention<B> {let state =state.map(|state| state.downcast::<AttentionState<B>>().expect("incorrect type of attention state"));-- // If we have gate we must duplicate input (linear does hadamard in-place). TODO: fix this properly by adding support for not in place input hadamard- let (hidden, gate) = if let Some(gate_projection) = &self.gate_projection {- let mut hidden_copy = encoder.allocate_scratch(hidden.size())?;- encoder.encode_copy(&hidden, .., &mut hidden_copy, ..);- let gate = gate_projection.encode(hidden, batch_dim.size(), encoder)?;- (hidden_copy, Some(gate))- } else {- (hidden, None)- };-- let mut qkv = self.qkv_projection.encode(hidden, batch_dim.size(), encoder)?;-- if let Some(qkv_norm) = &self.qkv_norm {- qkv_norm.encode(&mut qkv, batch_dim.size(), encoder)?;- }-- let mut queries = encoder- .allocate_scratch(size_for_shape(&[self.num_q_heads, batch_dim.size(), self.head_dim], self.data_type))?;-- let mut attention_output = if let Some(mut state) = state {- assert!(matches!(state, MaybeMut::Mut(_)) == !self.is_kv_sharing);-- let (prepare_keys, prepare_values, kv_token_offset) = match &mut state {- MaybeMut::Const(_) => (None, None, None),- MaybeMut::Mut(state) => (- Some(state.keys.as_mut()),- Some(state.values.as_mut()),- Some(state.state_type.physical_prefix_length()),- ),- };-- self.prepare.encode(- &qkv,- &mut queries,- prepare_keys,- prepare_values,- precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),- precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),- self.num_q_heads as u32,- self.num_kv_heads.map(|num_kv_heads| num_kv_heads as u32),- self.head_dim as u32,- precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),- kv_token_offset.map(|kv_token_offset| kv_token_offset as u32),- batch_dim.size() as u32,- encoder,- );-- let (core, trie) = if batch_dim.is_flat() {- (&self.flat_core, None)- } else {- let mut trie = encoder.allocate_constant(batch_dim.size() * size_of::<TrieNode>())?;- trie.copyin(batch_dim.nodes());- (&self.trie_core, Some(trie))- };-- core.encode(- AttentionCoreEncodeArguments {- queries: &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(),- state_type: &state.state_type,- },- encoder,- )?- } else {- let Some(num_kv_heads) = self.num_kv_heads else {- panic!("stateless attention doesn't support kv sharing");- };-- assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");-- let mut keys = encoder- .allocate_scratch(size_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type))?;- let mut values = encoder- .allocate_scratch(size_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type))?;-- self.prepare.encode(- &qkv,- &mut queries,- Some(&mut keys),- Some(&mut values),- precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),- precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),- self.num_q_heads as u32,- self.num_kv_heads.map(|num_kv_heads| num_kv_heads as u32),- self.head_dim as u32,- precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),- Some(0),- batch_dim.size() as u32,- encoder,- );-- // HACK: state_type should be Option.- let state_type = if self.sliding_window_size.is_some() {- AttentionStateType::Ring {- offset: 0,- length: 0,- max_length: 0,- }- } else {- AttentionStateType::Full {- length: 0,- }- };-- self.flat_core.encode(- AttentionCoreEncodeArguments {- queries: &queries,- keys: &keys,- values: &values,- suffix_length: batch_dim.size(),- trie: None,- sinks: self.sinks.as_ref(),- state_type: &state_type,- },- encoder,- )?- };-- if let Some(gate_kernel) = &self.gate_kernel {- gate_kernel.encode(- &gate.unwrap(),- &mut attention_output,- (batch_dim.size() * self.num_q_heads * self.head_dim) as u32,- encoder,- );- }- self.out_projection.encode(attention_output, batch_dim.size(), encoder)+ self.attend(hidden, precalculated_rope, batch_dim, state, encoder)}}diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/mode.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/mode.rsnew file mode 100644index 000000000..759c43cdb--- /dev/null+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/mode.rs@@ -0,0 +1,349 @@+use crate::{+ array::size_for_shape,+ backends::common::{+ Allocation, Backend, Encoder, Kernels,+ gpu_types::trie::TrieNode,+ kernel::{AttentionPrepareKernel, BufferArgMut, SigmoidGateKernel},+ },+ encodable_block::{+ batch_topology::BatchTopology,+ linear::Linear,+ mixer::attention::{+ Attention,+ core::AttentionCoreEncodeArguments,+ qkv_norm::QKVNorm,+ rope::PrecalculatedRoPE,+ state::{AttentionState, AttentionStateType},+ },+ },+ utils::maybe_mut::MaybeMut,+};++type PrepareKernel<B> = <<B as Backend>::Kernels as Kernels>::AttentionPrepareKernel;++pub(super) struct LinearProjection<B: Backend> {+ pub(super) lin: Box<dyn Linear<B>>,+ pub(super) norm: Option<QKVNorm<B>>,+}++impl<B: Backend> LinearProjection<B> {+ fn project(+ &self,+ hidden: Allocation<B>,+ batch_dim: usize,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ let mut projected = self.lin.encode(hidden, batch_dim, encoder)?;+ if let Some(norm) = &self.norm {+ norm.encode(&mut projected, batch_dim, encoder)?;+ }+ Ok(projected)+ }+}++pub(super) enum QkvProjection<B: Backend> {+ /// Fused QKV — or Q-only under KV sharing (`num_kv_heads == None`).+ Packed {+ qkv: LinearProjection<B>,+ prepare: PrepareKernel<B>,+ },+ /// Separate Q and KV projections.+ #[allow(dead_code)] // TODO: remove when wiring with DFlash.+ Split {+ q: LinearProjection<B>,+ kv: LinearProjection<B>,+ q_prepare: PrepareKernel<B>,+ kv_prepare: PrepareKernel<B>,+ },+}++impl<B: Backend> Attention<B> {+ pub(super) fn attend(+ &self,+ hidden: Allocation<B>,+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,+ batch_dim: &BatchTopology,+ state: Option<MaybeMut<AttentionState<B>>>,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ // If we have gate we must duplicate input (linear does hadamard in-place). TODO: fix this properly by adding support for not in place input hadamard+ let (hidden, gate) = if let Some(gate_projection) = &self.gate_projection {+ let mut hidden_copy = encoder.allocate_scratch(hidden.size())?;+ encoder.encode_copy(&hidden, .., &mut hidden_copy, ..);+ let gate = gate_projection.encode(hidden, batch_dim.size(), encoder)?;+ (hidden_copy, Some(gate))+ } else {+ (hidden, None)+ };++ let mut attention_output = match (&self.projection, state) {+ (+ QkvProjection::Packed {+ qkv,+ prepare,+ },+ Some(MaybeMut::Mut(state)),+ ) => {+ let qkv = qkv.project(hidden, batch_dim.size(), encoder)?;+ let queries = self.prepare_kv_and_queries(+ prepare,+ &qkv,+ state.keys.as_mut(),+ state.values.as_mut(),+ state.state_type.physical_prefix_length(),+ self.num_q_heads as u32,+ precalculated_rope,+ batch_dim.size(),+ encoder,+ )?;+ self.run_core(&queries, batch_dim, state, encoder)?+ },+ (+ QkvProjection::Packed {+ qkv,+ prepare,+ },+ Some(MaybeMut::Const(state)),+ ) => {+ // KV sharing: the packed projection produces queries only.+ let query = qkv.project(hidden, batch_dim.size(), encoder)?;+ let queries = self.prepare_queries(prepare, &query, precalculated_rope, batch_dim.size(), encoder)?;+ self.run_core(&queries, batch_dim, state, encoder)?+ },+ (+ QkvProjection::Packed {+ qkv,+ prepare,+ },+ 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 qkv = qkv.project(hidden, batch_dim.size(), encoder)?;+ let mut keys = encoder.allocate_scratch(size_for_shape(+ &[batch_dim.size(), num_kv_heads, self.head_dim],+ self.data_type,+ ))?;+ let mut values = encoder.allocate_scratch(size_for_shape(+ &[batch_dim.size(), num_kv_heads, self.head_dim],+ self.data_type,+ ))?;++ let queries = self.prepare_kv_and_queries(+ prepare,+ &qkv,+ &mut keys,+ &mut values,+ 0,+ self.num_q_heads as u32,+ precalculated_rope,+ batch_dim.size(),+ encoder,+ )?;++ // HACK: state_type should be Option.+ let state_type = if self.sliding_window_size.is_some() {+ AttentionStateType::Ring {+ offset: 0,+ length: 0,+ max_length: 0,+ }+ } else {+ AttentionStateType::Full {+ length: 0,+ }+ };++ self.flat_core.encode(+ AttentionCoreEncodeArguments {+ queries: &queries,+ keys: &keys,+ values: &values,+ suffix_length: batch_dim.size(),+ trie: None,+ sinks: self.sinks.as_ref(),+ state_type: &state_type,+ },+ encoder,+ )?+ },+ (+ QkvProjection::Split {+ q,+ kv,+ q_prepare,+ kv_prepare,+ },+ Some(MaybeMut::Mut(state)),+ ) => {+ // Linear::encode may consume/mutate its input; split Q/KV attention needs the same hidden for both projections.+ let mut hidden_for_key_value = encoder.allocate_scratch(hidden.size())?;+ encoder.encode_copy(&hidden, .., &mut hidden_for_key_value, ..);+ let query = q.project(hidden, batch_dim.size(), encoder)?;+ let key_value = kv.project(hidden_for_key_value, batch_dim.size(), encoder)?;+ let precalculated_rope = precalculated_rope.expect("split attention requires RoPE");+ let queries =+ self.prepare_queries(q_prepare, &query, Some(precalculated_rope), batch_dim.size(), encoder)?;+ self.prepare_kv_and_queries(+ kv_prepare,+ &key_value,+ state.keys.as_mut(),+ state.values.as_mut(),+ state.state_type.physical_prefix_length(),+ 0,+ Some(precalculated_rope),+ batch_dim.size(),+ encoder,+ )?;+ self.run_core(&queries, batch_dim, state, encoder)?+ },+ _ => panic!("attention projection/state combination is invalid"),+ };++ if let Some(gate_kernel) = &self.gate_kernel {+ gate_kernel.encode(+ &gate.unwrap(),+ &mut attention_output,+ (batch_dim.size() * self.num_q_heads * self.head_dim) as u32,+ encoder,+ );+ }+ self.out_projection.encode(attention_output, batch_dim.size(), encoder)+ }++ #[allow(dead_code)] // TODO: remove when wiring with DFlash.+ pub(super) fn append_kv(+ &self,+ hidden: Allocation<B>,+ precalculated_rope: &PrecalculatedRoPE<B>,+ batch_dim: usize,+ state: &mut AttentionState<B>,+ encoder: &mut Encoder<B>,+ ) -> Result<(), B::Error> {+ let QkvProjection::Split {+ kv,+ kv_prepare,+ ..+ } = &self.projection+ else {+ panic!("append-only attention requires split Q/KV projection");+ };+ let key_value = kv.project(hidden, batch_dim, encoder)?;+ self.prepare_kv_and_queries(+ kv_prepare,+ &key_value,+ state.keys.as_mut(),+ state.values.as_mut(),+ state.state_type.physical_prefix_length(),+ 0,+ Some(precalculated_rope),+ batch_dim,+ encoder,+ )?;+ state.append_full(batch_dim);+ Ok(())+ }++ fn run_core(+ &self,+ queries: &Allocation<B>,+ batch_dim: &BatchTopology,+ state: &AttentionState<B>,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ let (core, trie) = if batch_dim.is_flat() {+ (&self.flat_core, None)+ } else {+ let mut trie = encoder.allocate_constant(batch_dim.size() * size_of::<TrieNode>())?;+ trie.copyin(batch_dim.nodes());+ (&self.trie_core, Some(trie))+ };++ core.encode(+ AttentionCoreEncodeArguments {+ 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(),+ state_type: &state.state_type,+ },+ encoder,+ )+ }++ /// With `num_q_heads == 0`, only keys/values are scattered into the cache (KV append).+ fn prepare_kv_and_queries<'keys, 'values>(+ &self,+ prepare: &PrepareKernel<B>,+ input: &Allocation<B>,+ keys: impl BufferArgMut<'keys, B>,+ values: impl BufferArgMut<'values, B>,+ kv_token_offset: usize,+ num_q_heads: u32,+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,+ batch_dim: usize,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ let mut queries = if num_q_heads == 0 {+ encoder.allocate_scratch(self.data_type.size_in_bytes())?+ } else {+ self.allocate_queries(batch_dim, encoder)?+ };+ prepare.encode(+ input,+ &mut queries,+ Some(keys),+ Some(values),+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),+ num_q_heads,+ Some(self.num_kv_heads.expect("KV prepare requires KV heads") as u32),+ self.head_dim as u32,+ precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),+ Some(kv_token_offset as u32),+ batch_dim as u32,+ encoder,+ );+ Ok(queries)+ }++ fn prepare_queries(+ &self,+ prepare: &PrepareKernel<B>,+ query: &Allocation<B>,+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,+ batch_dim: usize,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ let mut queries = self.allocate_queries(batch_dim, encoder)?;+ prepare.encode(+ query,+ &mut queries,+ None::<&mut Allocation<B>>,+ None::<&mut Allocation<B>>,+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),+ self.num_q_heads as u32,+ None,+ self.head_dim as u32,+ precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),+ None,+ batch_dim as u32,+ encoder,+ );+ Ok(queries)+ }++ fn allocate_queries(+ &self,+ batch_dim: usize,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ encoder.allocate_scratch(size_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type))+ }+}diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rsindex 90f8673e3..92c8ae588 100644--- a/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs@@ -69,8 +69,6 @@ impl<B: Backend> AttentionState<B> {max_context_length: Option<usize>,context: &B::Context,) -> Result<Self, B::Error> {- assert!(attention.is_causal, "Non-causal attention cannot have state");-if let Some(max_context_length) = max_context_length {assert!(attention.max_rope_length.is_none_or(|max_rope_length| max_context_length <= max_rope_length),@@ -80,7 +78,9 @@ impl<B: Backend> AttentionState<B> {let data_type = attention.data_type;- let max_prefix_elements = if let Some(sliding_window_size) = attention.sliding_window_size {+ let max_prefix_elements = if attention.is_causal+ && let Some(sliding_window_size) = attention.sliding_window_size+ {sliding_window_size} else if let Some(max_context_length) = max_context_length {max_context_length@@ -90,16 +90,11 @@ impl<B: Backend> AttentionState<B> {.expect("Cannot create full attention state with unlimited length for with no RoPE")};- let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity- let max_elements = max_prefix_elements + suffix_capacity;- let element_size = attention.num_kv_heads.unwrap() * attention.head_dim;- let kv_buffer_bytes = max_elements * element_size * data_type.size_in_bytes();-- let state_type = if let Some(sliding_window_size) = attention.sliding_window_size {+ let state_type = if attention.is_causal && attention.sliding_window_size.is_some() {AttentionStateType::Ring {offset: 0,length: 0,- max_length: sliding_window_size,+ max_length: max_prefix_elements,}} else {AttentionStateType::Full {@@ -107,7 +102,12 @@ impl<B: Backend> AttentionState<B> {}};- let is_ring = attention.sliding_window_size.is_some();+ let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity+ let max_elements = max_prefix_elements + suffix_capacity;+ let element_size = attention.num_kv_heads.unwrap() * attention.head_dim;+ let kv_buffer_bytes = max_elements * element_size * data_type.size_in_bytes();++ let is_ring = matches!(state_type, AttentionStateType::Ring { .. });let is_sparse = !is_ring && context.sparse_buffers_supported();let (keys, values): (Box<dyn Buffer<Backend = B>>, Box<dyn Buffer<Backend = B>>) = if is_sparse {@@ -133,6 +133,21 @@ impl<B: Backend> AttentionState<B> {kv_cache_update,})}++ #[allow(dead_code)] // TODO: remove when wiring with DFlash.+ pub(super) fn append_full(+ &mut self,+ length: usize,+ ) {+ let AttentionStateType::Full {+ length: state_length,+ } = &mut self.state_type+ else {+ panic!("append_full requires full attention state");+ };+ *state_length += length;+ self.cur_context_length += length;+ }}impl<B: Backend> MixerState<B> for AttentionState<B> {