A high-performance inference engine for AI models
Model format 0.16.1 (qkvg + reasoning config) (#856)
uuuvn5c7d7219a23b
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rsindex 05726edd0..8c1ab4d7f 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs@@ -35,7 +35,7 @@ fn apply_rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(#[variants(ElementT, bf16)]#[variants(RopeT, f32)]pub fn attention_prepare<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(- qkv: *const ElementT,+ qkvg: *const ElementT,queries: *mut ElementT,#[optional(has_kv)] keys: Option<*mut ElementT>,#[optional(has_kv)] values: Option<*mut ElementT>,@@ -46,6 +46,7 @@ pub fn attention_prepare<ElementT: ArrayElement + Float, RopeT: ArrayElement + Fhead_dim: u32,#[optional(has_rope)] rope_dim: Option<u32>,#[optional(has_kv)] kv_token_offset: Option<u32>,+ input_row_stride: u32,batch_dim: u32,#[specialize] has_kv: bool,#[specialize] has_rope: bool,@@ -82,22 +83,24 @@ pub fn attention_prepare<ElementT: ArrayElement + Float, RopeT: ArrayElement + Flet num_q_heads = num_q_heads as usize;let head_dim = head_dim as usize;let batch_dim = batch_dim as usize;+ let input_row_stride = input_row_stride as usize;let total_heads = if has_kv {num_q_heads + num_kv_heads * 2} else {num_q_heads};+ assert!(input_row_stride >= total_heads * head_dim, "attention prepare row stride is too small");for batch_idx in 0..batch_dim {for head_idx in 0..total_heads {- let qkv_head = unsafe { qkv.add(batch_idx * total_heads * head_dim + head_idx * head_dim) };+ let qkvg_head = unsafe { qkvg.add(batch_idx * input_row_stride + head_idx * head_dim) };let is_query = !has_kv || head_idx < num_q_heads;let is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;for head_dim_idx in 0..head_dim {- let mut element = unsafe { *qkv_head.add(head_dim_idx) };+ let mut element = unsafe { *qkvg_head.add(head_dim_idx) };if has_rope && head_dim_idx < rope_dim && (is_query || is_key) {- element = apply_rope(qkv_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);+ element = apply_rope(qkvg_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);}if is_query {diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rsindex 007fd160a..cfb465b3d 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/qkv_norm.rs@@ -15,11 +15,11 @@ pub fn qkv_norm<OutputT: ArrayElement + Float,AccumT: ArrayElement + Float,>(- #[optional(!in_place)] qkv_input: Option<*const InputT>,+ #[optional(!in_place)] qkvg_input: Option<*const InputT>,#[optional(has_scales)] scales: Option<*const ScaleT>,- qkv_output: *mut OutputT,+ qkvg_output: *mut OutputT,batch_size: u32,- total_heads: u32,+ input_row_stride: u32,head_dim: u32,epsilon: f32,scale_offset: f32,@@ -29,33 +29,33 @@ pub fn qkv_norm<#[specialize] in_place: bool,#[specialize] has_scales: bool,) {- let qkv_input = match in_place {- true => qkv_output as *const InputT,- false => qkv_input.unwrap(),+ let qkvg_input = match in_place {+ true => qkvg_output as *const InputT,+ false => qkvg_input.unwrap(),};let head_dim = head_dim as usize;let head_offset = head_offset as usize;let head_count = head_count as usize;- let qkv_stride = total_heads as usize * head_dim;+ let input_row_stride = input_row_stride as usize;let head_dim_accum = AccumT::from(head_dim).unwrap();let epsilon = AccumT::from(epsilon).unwrap();let scale_offset = AccumT::from(scale_offset).unwrap();for batch in 0..(batch_size as usize) {for head in 0..head_count {- let offset = batch * qkv_stride + (head_offset + head) * head_dim;+ let offset = batch * input_row_stride + (head_offset + head) * head_dim;let mut total_sum = AccumT::zero();for i in 0..head_dim {- let input_val = unsafe { AccumT::from(*qkv_input.add(offset + i)).unwrap() };+ let input_val = unsafe { AccumT::from(*qkvg_input.add(offset + i)).unwrap() };total_sum = total_sum + input_val * input_val;}let mean_square: AccumT = total_sum / head_dim_accum;let rms_norm = AccumT::from((mean_square + epsilon).to_f32().unwrap().sqrt().recip()).unwrap();for i in 0..head_dim {- let input_val = unsafe { AccumT::from(*qkv_input.add(offset + i)).unwrap() };+ let input_val = unsafe { AccumT::from(*qkvg_input.add(offset + i)).unwrap() };let normalized: AccumT = input_val * rms_norm;let result: OutputT = if !has_scales {OutputT::from(normalized).unwrap()@@ -70,7 +70,7 @@ pub fn qkv_norm<normalized_low * scale_value_low}};- unsafe { *qkv_output.add(offset + i) = result };+ unsafe { *qkvg_output.add(offset + i) = result };}}}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rsindex dd3a07e25..d10807ad1 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/sigmoid_gate.rs@@ -9,14 +9,23 @@ use crate::array::ArrayElement;pub fn sigmoid_gate<T: ArrayElement + Float>(gate: *const T,output: *mut T,- total_elements: u32,+ gate_dim: u32,+ batch_dim: u32,+ gate_row_stride: u32,) {- for idx in 0..total_elements as usize {- unsafe {- let g = (*gate.add(idx)).to_f32().unwrap();+ assert!(gate_dim > 0, "sigmoid gate requires nonzero gate_dim");+ assert!(gate_row_stride >= gate_dim, "sigmoid gate row stride is too small");+ let gate_dim = gate_dim as usize;+ let batch_dim = batch_dim as usize;+ let gate_row_stride = gate_row_stride as usize;+ for batch_idx in 0..batch_dim {+ for gate_idx in 0..gate_dim {+ let output_idx = batch_idx * gate_dim + gate_idx;+ let gate_idx = batch_idx * gate_row_stride + gate_idx;+ let g = unsafe { (*gate.add(gate_idx)).to_f32().unwrap() };let sigmoid = 1.0f32 / (1.0f32 + (-g).exp());- let out = (*output.add(idx)).to_f32().unwrap();- *output.add(idx) = T::from(out * sigmoid).unwrap();+ let out = unsafe { (*output.add(output_idx)).to_f32().unwrap() };+ unsafe { *output.add(output_idx) = T::from(out * sigmoid).unwrap() };}}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metalindex 272505e95..07aee1240 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_prepare.metal@@ -27,7 +27,7 @@ template <typename ElementT, typename RopeT>VARIANTS(ElementT, bfloat)VARIANTS(RopeT, float)PUBLIC KERNEL(AttentionPrepare) (- const device ElementT* qkv, // [token, (q, k, v), head_dim]+ const device ElementT* qkvg, // [token, input_row_stride], with an optional trailing gatedevice ElementT* queries, // [head_idx, token, head_dim]device ElementT* keys OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]device ElementT* values OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]@@ -38,6 +38,7 @@ PUBLIC KERNEL(AttentionPrepare) (const constant uint32_t& head_dim,const constant uint32_t& rope_dim OPTIONAL(has_rope),const constant uint32_t& kv_token_offset OPTIONAL(has_kv),+ const constant uint32_t& input_row_stride,const constant uint32_t& batch_dim,const bool has_kv SPECIALIZE,const bool has_rope SPECIALIZE,@@ -45,15 +46,14 @@ PUBLIC KERNEL(AttentionPrepare) (const uint32_t head_idx AXIS(num_q_heads + num_kv_heads.unwrap_or(0) * 2, 1),const uint32_t batch_idx AXIS(batch_dim, 1)) {- const uint32_t total_heads = has_kv ? num_q_heads + num_kv_heads * 2 : num_q_heads;- const uint32_t qkv_head_idx = batch_idx * total_heads * head_dim + head_idx * head_dim;- const device ElementT* qkv_head = qkv + qkv_head_idx;+ const uint32_t qkvg_head_idx = batch_idx * input_row_stride + head_idx * head_dim;+ const device ElementT* qkvg_head = qkvg + qkvg_head_idx;const bool is_query = !has_kv || head_idx < num_q_heads;const bool is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;- ElementT element = qkv_head[head_dim_idx];+ ElementT element = qkvg_head[head_dim_idx];if (has_rope && head_dim_idx < rope_dim && (is_query || is_key)) {- element = apply_rope(qkv_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);+ element = apply_rope(qkvg_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);}if (is_query) {diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metalindex 373e729d7..1ddac82c7 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/qkv_norm.metal@@ -16,11 +16,11 @@ VARIANTS(ScaleT, float, bfloat)VARIANTS(OutputT, float, bfloat)VARIANTS(AccumT, float)PUBLIC KERNEL(QKVNorm)(- const device InputT* qkv_input OPTIONAL(!in_place),+ const device InputT* qkvg_input OPTIONAL(!in_place),const device ScaleT* scales OPTIONAL(has_scales),- device OutputT* qkv_output,+ device OutputT* qkvg_output,constant uint& batch_size,- constant uint& total_heads,+ constant uint& input_row_stride,constant uint& head_dim,constant float& epsilon,constant float& scale_offset,@@ -34,18 +34,18 @@ PUBLIC KERNEL(QKVNorm)(const bool has_scales SPECIALIZE) {if (in_place) {- qkv_input = (const device InputT*)qkv_output;+ qkvg_input = (const device InputT*)qkvg_output;}if (head_count == 0u || head_dim == 0u)return;const ulong slice_offset =- (ulong)batch_idx * (ulong)total_heads * (ulong)head_dim + (ulong)(head_offset + head_idx) * (ulong)head_dim;+ (ulong)batch_idx * (ulong)input_row_stride + (ulong)(head_offset + head_idx) * (ulong)head_dim;- const device InputT* input_data = qkv_input + slice_offset;+ const device InputT* input_data = qkvg_input + slice_offset;const device ScaleT* scales_data = scales;- device OutputT* output_data = qkv_output + slice_offset;+ device OutputT* output_data = qkvg_output + slice_offset;const uint element_count = head_dim;AccumT partial_sum = static_cast<AccumT>(0.0f);diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metalindex d49cb6b98..656d96237 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/sigmoid_gate.metal@@ -6,11 +6,13 @@ VARIANTS(T, float, bfloat)PUBLIC KERNEL(SigmoidGate)(const device T* gate,device T* output,- const constant uint& total_elements,- const uint tid AXIS(total_elements, 256)+ const constant uint& gate_dim,+ const constant uint& batch_dim,+ const constant uint& gate_row_stride,+ const uint gate_idx AXIS(gate_dim, 256),+ const uint batch_idx AXIS(batch_dim, 1)) {- if (tid >= total_elements)- return;- float sigmoid = 1.0f / (1.0f + exp(-float(gate[tid])));- output[tid] = T(float(output[tid]) * sigmoid);+ const uint output_idx = batch_idx * gate_dim + gate_idx;+ float sigmoid = 1.0f / (1.0f + exp(-float(gate[batch_idx * gate_row_stride + gate_idx])));+ output[output_idx] = T(float(output[output_idx]) * sigmoid);}diff --git a/crates/uzu-engine/src/config/token_codec/chat_codec.rs b/crates/uzu-engine/src/config/token_codec/chat_codec.rsindex 63ee8a27f..8a90b1bb9 100644--- a/crates/uzu-engine/src/config/token_codec/chat_codec.rs+++ b/crates/uzu-engine/src/config/token_codec/chat_codec.rs@@ -1,5 +1,12 @@use uzu_engine_macros::uzu_config;+#[uzu_config]+pub struct ReasoningConfig {+ pub default_reasoning_effort: String,+ pub field_name: String,+ pub reasoning_effort_to_field_value: serde_json::Map<String, serde_json::Value>,+}+#[uzu_config(super::TokenCodecConfig)]pub struct ChatCodecConfig {pub prompt_template: String,@@ -11,4 +18,6 @@ pub struct ChatCodecConfig {pub bos_token: Option<String>,pub end_of_thinking_tag: Option<String>,pub default_system_prompt: Option<String>,+ #[serde(default)] // TODO: ??? inconsistency in converted models in registry workaround, remove when resolved+ pub reasoning_config: Option<ReasoningConfig>,}diff --git a/crates/uzu-engine/src/config/token_mixer/attention.rs b/crates/uzu-engine/src/config/token_mixer/attention.rsindex 3cb4acad0..bcc9ff8a5 100644--- a/crates/uzu-engine/src/config/token_mixer/attention.rs+++ b/crates/uzu-engine/src/config/token_mixer/attention.rs@@ -7,7 +7,7 @@ use crate::config::{#[uzu_config(super::TokenMixerConfig)]pub struct AttentionConfig {- pub qkv_projection_config: LinearConfig,+ pub qkvg_projection_config: LinearConfig,pub out_projection_config: LinearConfig,pub query_norm_config: Option<NormalizationConfig>,@@ -21,9 +21,9 @@ pub struct AttentionConfig {pub sliding_window_size: Option<u32>,pub logit_soft_cap: Option<f32>,pub has_sinks: bool,- pub has_qkv_biases: bool,+ pub has_qkvg_biases: bool,pub has_out_biases: bool,- pub gate_projection_config: Option<LinearConfig>,+ pub has_gate: bool,pub normalize_values: bool,pub is_kv_sharing: bool,}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rsindex 3e7927833..64f199928 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs@@ -38,9 +38,9 @@ pub struct Attention<B: Backend> {ring_capacity: Option<u32>,max_rope_length: Option<u32>,data_type: DataType,- qkv: LinearProjection<B>,+ projection_dim: u32,+ projection: LinearProjection<B>,prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,- gate_projection: Option<Box<dyn Linear<B>>>,sinks: Option<Allocation<B>>,kernel: <B::Kernels as Kernels>::AttentionKernel,gate_kernel: Option<<B::Kernels as Kernels>::SigmoidGateKernel>,@@ -81,51 +81,26 @@ impl<B: Backend> Attention<B> {let q_dim = num_q_heads * head_dim;- let has_gate = config.gate_projection_config.is_some();-- // TODO: qkv and gate should be fused to be qkvg in lalamo- let qkv_projection_tree = parameter_tree.subtree("qkv_projection");- let qkv_projection_output_dimension = if let Some(num_kv_heads) = num_kv_heads {+ let projection_tree = parameter_tree.subtree("qkvg_projection");+ let qkv_dim = if let Some(num_kv_heads) = num_kv_heads {let kv_dim = num_kv_heads * head_dim;q_dim + kv_dim + kv_dim} else {q_dim};- let (qkv_projection, in_projection_input_hadamard_factors) = if !has_gate {- <dyn Linear<B>>::new_with_input_rht(- hidden_dim,- [qkv_projection_output_dimension],- config.has_qkv_biases,- context,- data_type,- &qkv_projection_tree,- )?+ let projection_dim = if config.has_gate {+ qkv_dim + q_dim} else {- (- <dyn Linear<B>>::new(- hidden_dim,- [qkv_projection_output_dimension],- config.has_qkv_biases,- context,- data_type,- &qkv_projection_tree,- )?,- None,- )+ qkv_dim};-- let gate_projection = has_gate- .then(|| {- <dyn Linear<B>>::new(- hidden_dim,- [q_dim],- false,- context,- data_type,- ¶meter_tree.subtree("gate_projection"),- )- })- .transpose()?;+ let (projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(+ hidden_dim,+ [projection_dim],+ config.has_qkvg_biases,+ context,+ data_type,+ &projection_tree,+ )?;let query_norm_config = config.query_norm_config.clone();// TODO: Fix lalamo config, those two must be None if kv sharing.@@ -142,6 +117,7 @@ impl<B: Backend> Attention<B> {parameter_tree,config.num_heads,num_kv_heads.unwrap_or(0), // TODO: should take option+ projection_dim,config.head_dim,)})@@ -180,7 +156,8 @@ impl<B: Backend> Attention<B> {).map_err(AttentionNewError::Backend)?;- let gate_kernel = has_gate+ let gate_kernel = config+ .has_gate.then(|| <B::Kernels as Kernels>::SigmoidGateKernel::new(context, data_type)).transpose().map_err(AttentionNewError::Backend)?;@@ -202,12 +179,12 @@ impl<B: Backend> Attention<B> {ring_capacity,max_rope_length,data_type,- qkv: LinearProjection {- lin: qkv_projection,+ projection_dim,+ projection: LinearProjection {+ lin: projection,norm: qkv_norm,},prepare,- gate_projection,sinks,kernel,gate_kernel,diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rsindex 863e5e21d..f03843486 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs@@ -44,22 +44,13 @@ impl<B: Backend> Attention<B> {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 qkvg = self.projection.project(hidden, batch_dim.size(), encoder)?;let mut attention_output = match state {Some(MaybeMut::Mut(state)) => {- let qkv = self.qkv.project(hidden, batch_dim.size(), encoder)?;let prefix_len = state.view().prefix_len();let queries = self.prepare_kv_and_queries(- &qkv,+ &qkvg,state.keys.as_mut(),state.values.as_mut(),prefix_len,@@ -71,9 +62,8 @@ impl<B: Backend> Attention<B> {self.run_core(&queries, batch_dim, state, encoder)?},Some(MaybeMut::Const(state)) => {- // KV sharing: the packed projection produces queries only.- let query = self.qkv.project(hidden, batch_dim.size(), encoder)?;- let queries = self.prepare_queries(&query, precalculated_rope, batch_dim.size(), encoder)?;+ // KV sharing: QKVG contains queries and an optional gate only.+ let queries = self.prepare_queries(&qkvg, precalculated_rope, batch_dim.size(), encoder)?;self.run_core(&queries, batch_dim, state, encoder)?},None => {@@ -82,14 +72,13 @@ impl<B: Backend> Attention<B> {};assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");- let qkv = self.qkv.project(hidden, batch_dim.size(), encoder)?;let mut keys = encoder.allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)?;let mut values = encoder.allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)?;let queries = self.prepare_kv_and_queries(- &qkv,+ &qkvg,&mut keys,&mut values,0,@@ -117,10 +106,14 @@ impl<B: Backend> Attention<B> {};if let Some(gate_kernel) = &self.gate_kernel {+ let gate_dim = self.num_q_heads * self.head_dim;+ let gate_offset = self.projection_dim - gate_dim;gate_kernel.encode(- &gate.unwrap(),+ (&qkvg, gate_offset as usize * self.data_type.size_in_bytes()),&mut attention_output,- batch_dim.size() * (self.num_q_heads * self.head_dim),+ gate_dim,+ batch_dim.size(),+ self.projection_dim,encoder,);}@@ -135,7 +128,7 @@ impl<B: Backend> Attention<B> {state: &mut AttentionState<B>,encoder: &mut Encoder<B>,) -> Result<(), B::Error> {- if let Some(norm) = &self.qkv.norm {+ if let Some(norm) = &self.projection.norm {norm.encode_key_value(&mut key_value, batch_dim, encoder)?;}let prefix_len = state.view().prefix_len();@@ -193,6 +186,13 @@ impl<B: Backend> Attention<B> {batch_dim: u32,encoder: &mut Encoder<B>,) -> Result<Allocation<B>, 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 input_row_stride = if num_q_heads == 0 {+ 2 * num_kv_heads * self.head_dim+ } else {+ self.projection_dim+ };let mut queries = if num_q_heads == 0 {encoder.allocate_scratch(self.data_type.size_in_bytes())?} else {@@ -206,10 +206,11 @@ impl<B: Backend> Attention<B> {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")),+ Some(num_kv_heads),self.head_dim,precalculated_rope.map(|precalculated_rope| precalculated_rope.dim),Some(kv_token_offset),+ input_row_stride,batch_dim,encoder,);@@ -218,7 +219,7 @@ impl<B: Backend> Attention<B> {fn prepare_queries(&self,- query: &Allocation<B>,+ qkvg: &Allocation<B>,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: u32,encoder: &mut Encoder<B>,@@ -226,7 +227,7 @@ impl<B: Backend> Attention<B> {let mut queries =encoder.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?;self.prepare.encode(- query,+ qkvg,&mut queries,None::<&mut Allocation<B>>,None::<&mut Allocation<B>>,@@ -237,6 +238,7 @@ impl<B: Backend> Attention<B> {self.head_dim,precalculated_rope.map(|rope| rope.dim),None,+ self.projection_dim,batch_dim,encoder,);diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rsindex 45eb93a93..81392f72a 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs@@ -30,6 +30,7 @@ pub struct QKVNorm<B: Backend> {value: Option<Head<B>>,num_q_heads: u32,num_kv_heads: u32,+ projection_row_stride: u32,head_dim: u32,}@@ -43,6 +44,7 @@ impl<B: Backend> QKVNorm<B> {parameter_tree: &ParameterTree<B>,num_q_heads: u32,num_kv_heads: u32,+ projection_row_stride: u32,head_dim: u32,) -> Result<Self, QKVNormError<B>> {let query = query_config@@ -77,6 +79,7 @@ impl<B: Backend> QKVNorm<B> {value,num_q_heads,num_kv_heads,+ projection_row_stride,head_dim,})}@@ -118,11 +121,11 @@ impl<B: Backend> QKVNorm<B> {pub fn encode(&self,- qkv: &mut Allocation<B>,+ qkvg: &mut Allocation<B>,batch_dim: u32,encoder: &mut Encoder<B>,) -> Result<(), B::Error> {- self.encode_packed(qkv, batch_dim, self.num_q_heads, encoder)+ self.encode_packed(qkvg, batch_dim, self.num_q_heads, self.projection_row_stride, encoder)}pub fn encode_key_value(@@ -131,7 +134,7 @@ impl<B: Backend> QKVNorm<B> {batch_dim: u32,encoder: &mut Encoder<B>,) -> Result<(), B::Error> {- self.encode_packed(key_value, batch_dim, 0, encoder)+ self.encode_packed(key_value, batch_dim, 0, 2 * self.num_kv_heads * self.head_dim, encoder)}fn encode_packed(@@ -139,12 +142,18 @@ impl<B: Backend> QKVNorm<B> {buffer: &mut Allocation<B>,batch_dim: u32,q_heads: u32,+ input_row_stride: u32,encoder: &mut Encoder<B>,) -> Result<(), B::Error> {+ let packed_row_width = (q_heads + 2 * self.num_kv_heads) * self.head_dim;+ assert!(+ input_row_stride >= packed_row_width,+ "QKV norm input row stride ({input_row_stride}) is smaller than its packed row width ({packed_row_width})"+ );+encoder.push_debug_group("qkv norm");let kv = self.num_kv_heads;- let total_heads = q_heads + 2 * kv;let heads = [(&self.query, 0, q_heads), (&self.key, q_heads, kv), (&self.value, q_heads + kv, kv)];for (head, head_offset, head_count) in heads {let Some(head) = head else {@@ -158,7 +167,7 @@ impl<B: Backend> QKVNorm<B> {head.scales.as_ref(),&mut *buffer,batch_dim,- total_heads,+ input_row_stride,self.head_dim,head.config.epsilon,head.config.scale_offset.unwrap_or(0.0),@@ -174,3 +183,7 @@ impl<B: Backend> QKVNorm<B> {Ok(())}}++#[cfg(test)]+#[path = "../../../../unit/encodable_block/attention/qkv_norm_test.rs"]+mod tests;diff --git a/crates/uzu-engine/src/encodable_block/weaver_layer.rs b/crates/uzu-engine/src/encodable_block/weaver_layer.rsindex 8c6a52468..b9a484775 100644--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs@@ -172,6 +172,7 @@ impl<B: Backend> WeaverLayer<B> {self.head_dim,Some(rope.dim),Some(0),+ 3 * self.model_dim,token_count,encoder,);diff --git a/crates/uzu-engine/src/utils/strict_serde.rs b/crates/uzu-engine/src/utils/strict_serde.rsindex 9cca71654..695f4e44c 100644--- a/crates/uzu-engine/src/utils/strict_serde.rs+++ b/crates/uzu-engine/src/utils/strict_serde.rs@@ -14,7 +14,7 @@ macro_rules! impl_strict {};}-impl_strict!(Unsupported, String, f32, u32, u64, usize, bool);+impl_strict!(Unsupported, String, f32, u32, u64, usize, bool, serde_json::Map<String, serde_json::Value>);impl<'de, T: DeserializeStrict<'de>> DeserializeStrict<'de> for Box<T> {}impl<'de, T: DeserializeStrict<'de>> DeserializeStrict<'de> for Box<[T]> {}diff --git a/crates/uzu-engine/src/utils/version.rs b/crates/uzu-engine/src/utils/version.rsindex 880f05502..695aeaea5 100644--- a/crates/uzu-engine/src/utils/version.rs+++ b/crates/uzu-engine/src/utils/version.rs@@ -1,2 +1,2 @@pub const VERSION: &str = env!("CARGO_PKG_VERSION");-pub const TOOLCHAIN_VERSION: &str = "0.15.1";+pub const TOOLCHAIN_VERSION: &str = "0.16.1";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.rsnew file mode 100644index 000000000..ea27e944c--- /dev/null+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs@@ -0,0 +1,130 @@+use half::bf16;+use uzu_engine_macros::uzu_test;++use crate::{+ backends::{+ common::{Allocation, Backend, Context, Encoder, Kernels, kernel::AttentionPrepareKernel},+ cpu::Cpu,+ },+ data_type::DataType,+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+};++struct Output {+ queries: Vec<bf16>,+ keys: Vec<bf16>,+ values: Vec<bf16>,+}++fn run<B: Backend>() -> Output {+ let context = B::Context::new().expect("Failed to create Context");+ let kernel = <<B as Backend>::Kernels as Kernels>::AttentionPrepareKernel::new(+ &context,+ DataType::BF16,+ DataType::F32,+ true,+ false,+ )+ .expect("Failed to create AttentionPrepareKernel");+ let qkvg = [+ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 101.0, 102.0, 103.0, 104.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0,+ 18.0, 111.0, 112.0, 113.0, 114.0,+ ]+ .map(bf16::from_f32);+ let qkvg = alloc_allocation_with_data::<B, bf16>(&context, &qkvg);+ let mut queries = alloc_allocation::<B, bf16>(&context, 8);+ let mut keys = alloc_allocation::<B, bf16>(&context, 4);+ let mut values = alloc_allocation::<B, bf16>(&context, 4);+ let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");++ kernel.encode(+ &qkvg,+ &mut queries,+ Some(&mut keys),+ Some(&mut values),+ None::<&Allocation<B>>,+ None::<&Allocation<B>>,+ 2,+ Some(1),+ 2,+ None,+ Some(0),+ 12,+ 2,+ &mut encoder,+ );+ encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");++ Output {+ queries: allocation_to_vec(&queries),+ keys: allocation_to_vec(&keys),+ values: allocation_to_vec(&values),+ }+}++fn assert_output(+ output: Output,+ backend: &str,+) {+ let expected_queries = [1.0, 2.0, 11.0, 12.0, 3.0, 4.0, 13.0, 14.0].map(bf16::from_f32);+ let expected_keys = [5.0, 6.0, 15.0, 16.0].map(bf16::from_f32);+ let expected_values = [7.0, 8.0, 17.0, 18.0].map(bf16::from_f32);++ assert_eq!(output.queries, expected_queries, "query mismatch on {backend}");+ assert_eq!(output.keys, expected_keys, "key mismatch on {backend}");+ assert_eq!(output.values, expected_values, "value mismatch on {backend}");+}++fn run_query_only<B: Backend>() -> Vec<bf16> {+ let context = B::Context::new().expect("Failed to create Context");+ let kernel = <<B as Backend>::Kernels as Kernels>::AttentionPrepareKernel::new(+ &context,+ DataType::BF16,+ DataType::F32,+ false,+ false,+ )+ .expect("Failed to create AttentionPrepareKernel");+ let qg = [1.0, 2.0, 3.0, 4.0, 101.0, 102.0, 103.0, 104.0, 11.0, 12.0, 13.0, 14.0, 111.0, 112.0, 113.0, 114.0]+ .map(bf16::from_f32);+ let qg = alloc_allocation_with_data::<B, bf16>(&context, &qg);+ let mut queries = alloc_allocation::<B, bf16>(&context, 8);+ let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");++ kernel.encode(+ &qg,+ &mut queries,+ None::<&mut Allocation<B>>,+ None::<&mut Allocation<B>>,+ None::<&Allocation<B>>,+ None::<&Allocation<B>>,+ 2,+ None,+ 2,+ None,+ None,+ 8,+ 2,+ &mut encoder,+ );+ encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");++ allocation_to_vec(&queries)+}++#[uzu_test]+fn test_attention_prepare_uses_qkvg_row_stride() {+ assert_output(run::<Cpu>(), "CPU");+ for_each_non_cpu_backend!(|B| {+ assert_output(run::<B>(), std::any::type_name::<B>());+ });+}++#[uzu_test]+fn test_attention_prepare_uses_query_gate_row_stride() {+ let expected = [1.0, 2.0, 11.0, 12.0, 3.0, 4.0, 13.0, 14.0].map(bf16::from_f32);+ assert_eq!(run_query_only::<Cpu>(), expected, "query mismatch on CPU");+ for_each_non_cpu_backend!(|B| {+ assert_eq!(run_query_only::<B>(), expected, "query mismatch on {}", std::any::type_name::<B>());+ });+}diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rsindex 44cda3596..f23375caf 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/mod.rs@@ -1,4 +1,5 @@mod ancestor_attention_test;+mod attention_prepare_test;mod kv_cache_update_test;mod qkv_norm_test;mod sigmoid_gate_test;diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rsindex 6f7ce5b4a..9b9cd02f5 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs@@ -18,11 +18,12 @@ use crate::{};struct Input<InputT: ArrayElement + Float, ScaleT: ArrayElement + Float, OutputT: ArrayElement + Float> {- qkv: Box<[OutputT]>,+ qkvg: Box<[OutputT]>,scales: Box<[ScaleT]>,batch_size: u32,num_q_heads: u32,num_kv_heads: u32,+ input_row_stride: u32,head_dim: u32,epsilon: f32,scale_offset: f32,@@ -89,11 +90,12 @@ fn get_test_data<let qkv_data: Vec<OutputT> = qkv_data_f32.iter().map(|&x| OutputT::from(x).unwrap()).collect();let input = Input {- qkv: qkv_data.into_boxed_slice(),+ qkvg: qkv_data.into_boxed_slice(),scales: scale_data.into_boxed_slice(),batch_size,num_q_heads,num_kv_heads,+ input_row_stride: qkv_width as u32,head_dim,epsilon,scale_offset,@@ -131,16 +133,16 @@ fn get_output<).expect("Failed to create QKVNormKernel");- let mut qkv = alloc_allocation_with_data::<B, OutputT>(&context, &input.qkv);+ let mut qkvg = alloc_allocation_with_data::<B, OutputT>(&context, &input.qkvg);let scales = input.has_scales.then(|| alloc_allocation_with_data::<B, ScaleT>(&context, &input.scales));let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");kernel.encode(None::<&Allocation<B>>,scales.as_ref(),- &mut qkv,+ &mut qkvg,input.batch_size,- input.num_q_heads + 2 * input.num_kv_heads,+ input.input_row_stride,input.head_dim,input.epsilon,input.scale_offset,@@ -151,7 +153,7 @@ fn get_output<);encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- allocation_to_vec(&qkv)+ allocation_to_vec(&qkvg)}fn test_internal<@@ -234,14 +236,14 @@ fn test_addressing<let num_q_heads = input.num_q_heads as usize;let head_dim = input.head_dim as usize;let k_start = num_q_heads * head_dim;- let qkv_len = input.qkv.len();+ let qkv_len = input.qkvg.len();for_each_non_cpu_backend!(|B| {let output = get_output::<B, InputT, ScaleT, OutputT, AccumT>(&input);// Q heads should be modified (different from input)for i in 0..(num_q_heads * head_dim) {- let orig = input.qkv[i].to_f32().unwrap();+ let orig = input.qkvg[i].to_f32().unwrap();let out = output[i].to_f32().unwrap();assert!((out - orig).abs() > 0.001,@@ -253,7 +255,7 @@ fn test_addressing<// K and V heads should be unchangedfor i in k_start..qkv_len {- let orig = input.qkv[i].to_f32().unwrap();+ let orig = input.qkvg[i].to_f32().unwrap();let out = output[i].to_f32().unwrap();assert!((out - orig).abs() < 1e-6,@@ -280,13 +282,13 @@ fn test_v_addressing<let num_kv_heads = input.num_kv_heads as usize;let head_dim = input.head_dim as usize;let v_start = (num_q_heads + num_kv_heads) * head_dim;- let qkv_len = input.qkv.len();+ let qkv_len = input.qkvg.len();for_each_non_cpu_backend!(|B| {let output = get_output::<B, InputT, ScaleT, OutputT, AccumT>(&input);for i in 0..v_start {- let orig = input.qkv[i].to_f32().unwrap();+ let orig = input.qkvg[i].to_f32().unwrap();let out = output[i].to_f32().unwrap();assert!((out - orig).abs() < 1e-6,@@ -299,7 +301,7 @@ fn test_v_addressing<}for i in v_start..qkv_len {- let orig = input.qkv[i].to_f32().unwrap();+ let orig = input.qkvg[i].to_f32().unwrap();let out = output[i].to_f32().unwrap();assert!((out - orig).abs() > 0.001,@@ -311,6 +313,47 @@ fn test_v_addressing<});}+#[uzu_test]+fn test_gated_row_stride() {+ let (input, _) = get_test_data::<f32, f32, f32, f32>(0, 4, false, false);+ let qkv_row = input.qkvg.to_vec();+ let gate_len = (input.num_q_heads * input.head_dim) as usize;+ let qkv_len = qkv_row.len();+ let input_row_stride = qkv_len + gate_len;+ let qkvg = (0..2)+ .flat_map(|batch| {+ qkv_row.iter().copied().chain((0..gate_len).map(move |index| 10.0 + batch as f32 + index as f32 * 0.01))+ })+ .collect::<Vec<_>>()+ .into_boxed_slice();+ let input = Input {+ qkvg,+ batch_size: 2,+ input_row_stride: input_row_stride as u32,+ ..input+ };++ let assert_addressing = |output: &[f32], backend: &str| {+ for batch in 0..input.batch_size as usize {+ let row_offset = batch * input_row_stride;+ for index in row_offset..row_offset + (input.num_q_heads * input.head_dim) as usize {+ assert_ne!(output[index], input.qkvg[index], "Q was not normalized on {backend}");+ }+ for index in row_offset + qkv_len..row_offset + input_row_stride {+ assert_eq!(output[index], input.qkvg[index], "gate was modified on {backend}");+ }+ }+ };++ let expected = get_output::<Cpu, f32, f32, f32, f32>(&input);+ assert_addressing(&expected, "CPU");+ for_each_non_cpu_backend!(|B| {+ let output = get_output::<B, f32, f32, f32, f32>(&input);+ assert_addressing(&output, std::any::type_name::<B>());+ assert_eq_float(&expected, &output, 1e-5, "QKVG row stride mismatch");+ });+}+// Q norm tests#[uzu_test]fn test_q_norm_f32_f32_f32_f32() {diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rsindex 5f668e5f7..6f5524def 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs@@ -15,12 +15,13 @@ use crate::{struct Config {num_heads: u32,+ num_kv_heads: u32,head_dim: u32,suffix_length: u32,}fn get_output<T: ArrayElement + Float, B: Backend>(- gate_data: &[T],+ qkvg_data: &[T],output_data: &[T],config: &Config,) -> Vec<T> {@@ -28,12 +29,21 @@ fn get_output<T: ArrayElement + Float, B: Backend>(let kernel = <<B as Backend>::Kernels as Kernels>::SigmoidGateKernel::new(&context, T::data_type()).expect("Failed to create SigmoidGateKernel");- let gate_allocation = alloc_allocation_with_data::<B, T>(&context, gate_data);+ let qkvg = alloc_allocation_with_data::<B, T>(&context, qkvg_data);let mut output = alloc_allocation_with_data::<B, T>(&context, output_data);let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- let total_elements = config.suffix_length * config.num_heads * config.head_dim;- kernel.encode(&gate_allocation, &mut output, total_elements, &mut encoder);+ let gate_dim = config.num_heads * config.head_dim;+ let gate_offset = (config.num_heads + 2 * config.num_kv_heads) * config.head_dim;+ let qkvg_dim = gate_offset + gate_dim;+ kernel.encode(+ (&qkvg, gate_offset as usize * size_of::<T>()),+ &mut output,+ gate_dim,+ config.suffix_length,+ qkvg_dim,+ &mut encoder,+ );encoder.end_encoding().submit().wait_until_completed().unwrap();allocation_to_vec(&output)@@ -41,14 +51,34 @@ fn get_output<T: ArrayElement + Float, B: Backend>(fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {let size = (config.suffix_length * config.num_heads * config.head_dim) as usize;-- let gate_f32: Vec<f32> = (0..size).map(|i| (i as f32) * 0.1 - 2.0).collect();+ let gate_dim = (config.num_heads * config.head_dim) as usize;+ let gate_offset = ((config.num_heads + 2 * config.num_kv_heads) * config.head_dim) as usize;+ let qkvg_dim = gate_offset + gate_dim;++ let qkvg_f32 = (0..config.suffix_length as usize)+ .flat_map(|row| {+ (0..qkvg_dim).map(move |column| {+ if column < gate_offset {+ return -100.0;+ }+ let gate_index = row * gate_dim + column - gate_offset;+ (gate_index as f32) * 0.1 - 2.0+ })+ })+ .collect::<Vec<_>>();let output_f32: Vec<f32> = (0..size).map(|i| (i as f32) * 0.05 + 0.5).collect();- let gate_data: Vec<T> = gate_f32.iter().map(|&v| T::from(v).unwrap()).collect();+ let qkvg_data: Vec<T> = qkvg_f32.iter().map(|&v| T::from(v).unwrap()).collect();let output_data: Vec<T> = output_f32.iter().map(|&v| T::from(v).unwrap()).collect();-- let expected = get_output::<T, Cpu>(&gate_data, &output_data, config);+ let expected = (0..size)+ .map(|output_index| {+ let batch_index = output_index / gate_dim;+ let gate_index = output_index % gate_dim;+ let gate = qkvg_data[batch_index * qkvg_dim + gate_offset + gate_index].to_f32().unwrap();+ let sigmoid = 1.0 / (1.0 + (-gate).exp());+ T::from(output_data[output_index].to_f32().unwrap() * sigmoid).unwrap()+ })+ .collect::<Vec<_>>();let rtol = if std::mem::size_of::<T>() <= 2 {0.01@@ -56,9 +86,7 @@ fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {1e-5};- for_each_non_cpu_backend!(|B| {- let result = get_output::<T, B>(&gate_data, &output_data, config);-+ let assert_output = |result: &[T], backend: &str| {for (i, (got, exp)) in result.iter().zip(expected.iter()).enumerate() {let got_f32 = got.to_f32().unwrap();let exp_f32 = exp.to_f32().unwrap();@@ -67,7 +95,7 @@ fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {assert!(diff < tol,"Backend {}: mismatch at index {}: got {} expected {} (diff {}, tol {})",- std::any::type_name::<B>(),+ backend,i,got_f32,exp_f32,@@ -75,6 +103,13 @@ fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {tol,);}+ };++ let result = get_output::<T, Cpu>(&qkvg_data, &output_data, config);+ assert_output(&result, std::any::type_name::<Cpu>());+ for_each_non_cpu_backend!(|B| {+ let result = get_output::<T, B>(&qkvg_data, &output_data, config);+ assert_output(&result, std::any::type_name::<B>());});}@@ -82,16 +117,19 @@ fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {fn test_sigmoid_gate_f32() {run_test::<f32>(&Config {num_heads: 8,+ num_kv_heads: 2,head_dim: 64,suffix_length: 4,});run_test::<f32>(&Config {num_heads: 16,+ num_kv_heads: 4,head_dim: 256,suffix_length: 1,});run_test::<f32>(&Config {num_heads: 2,+ num_kv_heads: 1,head_dim: 64,suffix_length: 8,});@@ -101,11 +139,13 @@ fn test_sigmoid_gate_f32() {fn test_sigmoid_gate_bf16() {run_test::<bf16>(&Config {num_heads: 8,+ num_kv_heads: 2,head_dim: 64,suffix_length: 4,});run_test::<bf16>(&Config {num_heads: 16,+ num_kv_heads: 4,head_dim: 256,suffix_length: 1,});diff --git a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rsnew file mode 100644index 000000000..fb554efe6--- /dev/null+++ b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs@@ -0,0 +1,70 @@+use uzu_engine_macros::uzu_test;++use super::QKVNorm;+use crate::{+ backends::common::{Backend, Encoder},+ config::normalization::{NormalizationConfig, UpcastMode},+ data_type::DataType,+ tests::{+ assert::assert_eq_float,+ helpers::{alloc_allocation_with_data, allocation_to_vec, create_context, for_each_backend},+ },+};++fn run_key_value_row_stride_test<B: Backend>() {+ const BATCH_SIZE: u32 = 2;+ const NUM_KV_HEADS: u32 = 2;+ const HEAD_DIM: u32 = 4;+ const ROW_WIDTH: u32 = 2 * NUM_KV_HEADS * HEAD_DIM;+ const EPSILON: f32 = 1e-6;++ let context = create_context::<B>();+ let config = NormalizationConfig {+ epsilon: EPSILON,+ scale_offset: None,+ upcast_mode: UpcastMode::OnlyNormalization,+ subtract_mean: false,+ has_scale: false,+ has_biases: false,+ };+ let key = QKVNorm::<B>::build_head(&context, DataType::F32, config, None, HEAD_DIM)+ .expect("failed to construct key norm");+ let norm = QKVNorm {+ query: None,+ key: Some(key),+ value: None,+ num_q_heads: 0,+ num_kv_heads: NUM_KV_HEADS,+ projection_row_stride: ROW_WIDTH,+ head_dim: HEAD_DIM,+ };++ let row_width = ROW_WIDTH as usize;+ let head_dim = HEAD_DIM as usize;+ let input = (0..BATCH_SIZE as usize * row_width).map(|index| 1.0 + index as f32 * 0.125).collect::<Vec<_>>();+ let mut expected = input.clone();+ for batch in 0..BATCH_SIZE as usize {+ for head in 0..NUM_KV_HEADS as usize {+ let start = batch * row_width + head * head_dim;+ let mean_square =+ input[start..start + head_dim].iter().map(|value| value * value).sum::<f32>() / HEAD_DIM as f32;+ let inverse_rms = (mean_square + EPSILON).sqrt().recip();+ for index in start..start + head_dim {+ expected[index] *= inverse_rms;+ }+ }+ }++ let mut key_value = alloc_allocation_with_data::<B, f32>(&context, &input);+ let mut encoder = Encoder::new(context.as_ref()).expect("failed to create encoder");+ norm.encode_key_value(&mut key_value, BATCH_SIZE, &mut encoder).expect("failed to encode key/value norm");+ encoder.end_encoding().submit().wait_until_completed().expect("failed to execute key/value norm");++ let output = allocation_to_vec::<B, f32>(&key_value);+ assert_eq_float(&expected, &output, 1e-5, "key/value norm row stride mismatch");+}++#[uzu_test]+fn test_key_value_norm_uses_element_row_stride() {+ for_each_backend!(|B| run_key_value_row_stride_test::<B>());+}