diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs index a42d7485..06daa3ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs @@ -5,11 +5,11 @@ use super::*; use crate::qwen_forward::gr::ResidualReady; use crate::qwen_forward::qsa_attention::QsaReady; use crate::qwen_forward::qsa_attention::{ - NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch, + NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch, PromptDevices, }; use crate::qwen_forward::qsa_native_resources::NativeQsaResources; use crate::qwen_forward::qsa_prefill_batch::NativeProjectionRow; -use crate::qwen_forward::qsa_prompt_index; +use crate::qwen_forward::qsa_prompt_index::{self, PromptChunkOwners, PromptIndexDevices}; use leleka_cuda_driver::{QsaPromptAttention, QsaPromptIndexWorkspace, QsaPromptKv, QsaPromptStage}; /// The index workspace, stage, attention and KV owners of the native QSA prompt. @@ -96,10 +96,13 @@ fn qsa_native_complete<'source, 'lease, 'own, 'ctx>( let prior = chunk.prompt_native_qsa_prior(layer, kv)?; let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; let owner = index.as_mut().ok_or(Error::IdentityMismatch)?; - let index = qsa_prompt_index::prepare(binding, cache, chunk, layer, &prior, native, owner, &mut workspace)?; + let owners = PromptChunkOwners { binding, cache, chunk }; + let index_devices = PromptIndexDevices { owner, workspace: &mut workspace }; + let index = qsa_prompt_index::prepare(owners, layer, &prior, native, index_devices)?; let stage = stage.as_mut().ok_or(Error::IdentityMismatch)?; let attention = prompt_attention.as_mut().ok_or(Error::IdentityMismatch)?; - let completed = Batch::complete(binding, cache, chunk, layer, index, &prior, kv, stage, attention, &mut workspace)?; + let devices = PromptDevices { kv, stage, attention, workspace: &mut workspace }; + let completed = Batch::complete(owners, layer, index, &prior, devices)?; drop(workspace); Ok(completed) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs index 4cbd29a1..b012198c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs @@ -3,8 +3,8 @@ use super::contract::{Error, LayerId, Result, Stage, TokenLayer}; use super::dense_weight_cache::DenseWeightCache; use super::qsa_index::{ - QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project, project_cached_out, - release, upload, upload_bytes, validate_values, + QsaAttendBuffers, QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project, + project_cached_out, release, upload, upload_bytes, validate_values, }; use super::session::QwenStepTxn; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, QsaMatrixRole}; @@ -107,6 +107,8 @@ mod impl_qsaready; use impl_qsaready::decode_cached; mod decode_selected_cached_fn; #[allow(unused_imports)] +use decode_selected_cached_fn::SelectedKvBytes; +#[allow(unused_imports)] use decode_selected_cached_fn::attend_retained; #[allow(unused_imports)] use decode_selected_cached_fn::attention_driver_error; @@ -121,3 +123,5 @@ use decode_selected_cached_fn::upload_retained_bytes; #[allow(unused_imports)] use decode_selected_cached_fn::upload_retained_f32; mod impl_nativeattended; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(super) use impl_nativeattended::PromptDevices; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs index d27a0374..790a1572 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs @@ -14,7 +14,8 @@ pub(super) fn decode_selected_cached( let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; let (mut q, mut y) = (None, None); - let result = attend_selected(binding, prepared, context, selected, &failed, (&mut q, &mut y)); + let retained = RetainedAttend { query: &mut q, output: &mut y, failed: &failed }; + let result = attend_selected(binding, prepared, context, selected, retained); let cleanup = release_retained([q]); let values = settle_retained(result, cleanup, &mut y, &failed)?; let attended = QsaAttended { context, buffer: y, values, failed }; @@ -26,20 +27,27 @@ pub(super) fn decode_selected_cached( validate_values(&output, 2560)?; Ok(QsaReady { identity: prepared.identity(), binding: binding.identity(), output }) } +/// The retained query and output buffers of one selected-cache attend pass and the shared failure fence they settle +/// against. +struct RetainedAttend<'a, 'ctx> { + query: &'a mut Option>, + output: &'a mut Option>, + failed: &'a Cell, +} /// The selected cache attends the uploaded query into `y`; the output is read back whole. fn attend_selected<'ctx>( binding: &ModelBinding, prepared: &QsaPrepared, context: &'ctx Context<'ctx>, selected: &mut QsaSelectedCache<'_>, - failed: &Cell, - (q, y): (&mut Option>, &mut Option>), + retained: RetainedAttend<'_, 'ctx>, ) -> Result> { + let RetainedAttend { query: q, output: y, failed } = retained; validate_values(prepared.q(), Q)?; *q = Some(upload_retained_f32(context, prepared.q(), failed)?); *y = Some(allocate(context, Q)?); let (query, output) = (q.as_ref().ok_or(Error::CudaExecution)?, y.as_mut().ok_or(Error::CudaExecution)?); - selected.attend(&binding.identity(), context, prepared, query, output)?; + selected.attend(&binding.identity(), context, prepared, QsaAttendBuffers { query, output })?; // Full original finite boundary remains before gating can mask an invalid value. download(y.as_ref().ok_or(Error::CudaExecution)?, Q) } @@ -63,6 +71,13 @@ fn settle_retained( output_cleanup?; Err(Error::CudaExecution) } +/// The canonical FP16 key and value bytes of the `width` selected cells one QSA attention pass reads. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct SelectedKvBytes<'a> { + pub(in crate::qwen_forward) keys: &'a [u8], + pub(in crate::qwen_forward) values: &'a [u8], + pub(in crate::qwen_forward) width: u32, +} #[derive(Default)] struct AttendBuffers<'ctx> { q: Option>, @@ -89,10 +104,10 @@ impl<'ctx> AttendBuffers<'ctx> { &mut self, context: &'ctx Context<'ctx>, query: &[f32], - (keys, values): (&[u8], &[u8]), - width: u32, + kv: SelectedKvBytes<'_>, failed: &Cell, ) -> Result> { + let SelectedKvBytes { keys, values, width } = kv; self.upload(context, query, (keys, values), failed)?; let (q, k, v) = (self.q.as_ref(), self.k.as_ref(), self.v.as_ref()); let (q, k, v) = @@ -108,17 +123,15 @@ impl<'ctx> AttendBuffers<'ctx> { pub(super) fn attend_retained<'ctx>( context: &'ctx Context<'ctx>, query: &[f32], - keys: &[u8], - values: &[u8], - width: u32, + kv: SelectedKvBytes<'_>, failed: Rc>, ) -> Result> { if failed.get() { return Err(Error::CudaExecution); } - check_attend(query, keys, values, width)?; + check_attend(query, kv.keys, kv.values, kv.width)?; let mut buffers = AttendBuffers::default(); - let result = buffers.launch(context, query, (keys, values), width, &failed); + let result = buffers.launch(context, query, kv, &failed); let cleanup = release_retained([buffers.q.take(), buffers.k.take(), buffers.v.take()]); let read = settle_retained(result, cleanup, &mut buffers.y, &failed)?; Ok(QsaAttended { context, buffer: buffers.y, values: read, failed }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs index f75c33a5..e3605bb7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs @@ -2,6 +2,8 @@ #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::qsa_index::QsaPending; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::super::qsa_prompt_index::PromptChunkOwners; #[allow(unused_imports)] use super::*; @@ -95,26 +97,20 @@ impl NativeAttended<'_, '_> { } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { - #[allow(clippy::too_many_arguments)] pub(in super::super) fn complete( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>, + owners: PromptChunkOwners<'_, 'ctx, '_, '_>, layer: LayerId, index: super::super::qsa_prompt_index::PromptIndexBatch<'source, 'lease, 'ctx>, prior: &super::super::qsa_index::QsaPrior, - kv: &mut leleka_cuda_driver::QsaPromptKv<'ctx>, - stage: &mut leleka_cuda_driver::QsaPromptStage<'ctx>, - attention: &mut leleka_cuda_driver::QsaPromptAttention<'ctx>, - workspace: &mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>, + mut devices: PromptDevices<'_, 'ctx>, ) -> Result { + let PromptChunkOwners { binding, cache, chunk } = owners; let (context, origin) = Self::owner(binding, cache, chunk)?; chunk.validate_prompt_qsa_prior(layer, prior)?; - let snapshot = prior.native_snapshot(kv)?.clone(); + let snapshot = prior.native_snapshot(devices.kv)?.clone(); let t = index.rows(); - let mut devices = PromptDevices { kv, stage, attention, workspace }; - let append = devices.append(&index, binding, cache, chunk, &snapshot)?; - let values = devices.attend(&index, binding, cache, chunk, &append)?; + let append = devices.append(&index, owners, &snapshot)?; + let values = devices.attend(&index, owners, &append)?; validate_values(&values, t * Q)?; chunk.validate_prompt_qsa_prior(layer, prior)?; let provider = cache.qsa(binding, layer.get())?.weights.clone(); @@ -228,11 +224,11 @@ type RowWords = (Box<[f32]>, Box<[f32]>); /// The prompt KV, its stage, the attention and the workspace of one native QSA layer. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -struct PromptDevices<'a, 'ctx> { - kv: &'a mut leleka_cuda_driver::QsaPromptKv<'ctx>, - stage: &'a mut leleka_cuda_driver::QsaPromptStage<'ctx>, - attention: &'a mut leleka_cuda_driver::QsaPromptAttention<'ctx>, - workspace: &'a mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>, +pub(in crate::qwen_forward) struct PromptDevices<'a, 'ctx> { + pub(in crate::qwen_forward) kv: &'a mut leleka_cuda_driver::QsaPromptKv<'ctx>, + pub(in crate::qwen_forward) stage: &'a mut leleka_cuda_driver::QsaPromptStage<'ctx>, + pub(in crate::qwen_forward) attention: &'a mut leleka_cuda_driver::QsaPromptAttention<'ctx>, + pub(in crate::qwen_forward) workspace: &'a mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>, } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> PromptDevices<'_, 'ctx> { @@ -240,11 +236,10 @@ impl<'ctx> PromptDevices<'_, 'ctx> { fn append( &mut self, index: &super::super::qsa_prompt_index::PromptIndexBatch<'_, '_, 'ctx>, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>, + owners: PromptChunkOwners<'_, 'ctx, '_, '_>, snapshot: &leleka_cuda_driver::QsaKvSnapshot, ) -> Result { + let PromptChunkOwners { binding, cache, chunk } = owners; let t = index.rows(); let append = index.with_completed_before_causal(binding, cache, chunk, |k, v, _, _, _| { let inputs = leleka_cuda_driver::QsaKvInputs::new(k, v, t).map_err(attention_driver_error)?; @@ -264,11 +259,10 @@ impl<'ctx> PromptDevices<'_, 'ctx> { fn attend( &mut self, index: &super::super::qsa_prompt_index::PromptIndexBatch<'_, '_, 'ctx>, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>, + owners: PromptChunkOwners<'_, 'ctx, '_, '_>, append: &leleka_cuda_driver::CompletedQsaKvAppend, ) -> Result> { + let PromptChunkOwners { binding, cache, chunk } = owners; let t = index.rows(); index.with_completed_before_causal(binding, cache, chunk, |_, _, q, ids, steps| { let inputs = diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs index aa86874f..5ab9b2ef 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs @@ -3,9 +3,10 @@ #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::{ qsa_decode_attention::{NativeDecodeAttentionRow, NativeDecodeDevices, complete}, - qsa_decode_index::QsaDecodeIndex, + qsa_decode_index::{DecodeStepOwners, QsaDecodeIndex}, qsa_index::QsaPrior, qsa_native_resources::NativeQsaResources, + qsa_prompt_index::PromptIndexDevices, }; #[allow(unused_imports)] use super::*; @@ -60,7 +61,9 @@ impl QsaAttentionStage { let kv = kv.get_mut(slot).ok_or(Error::InvalidLayer)?; let prior = txn.native_qsa_prior(layer, kv)?; let index = index.as_mut().ok_or(Error::IdentityMismatch)?; - let selected = QsaDecodeIndex::prepare(binding, cache, txn, layer, input, &prior, index, workspace)?; + let owners = DecodeStepOwners { binding, cache, txn }; + let devices = PromptIndexDevices { owner: index, workspace: &mut *workspace }; + let selected = QsaDecodeIndex::prepare(owners, layer, input, &prior, devices)?; let devices = NativeDecodeDevices::bind(decode, kv, stage, gate, workspace)?; let completed = complete(binding, cache, txn, layer, input, &prior, selected, devices)?; Ok((prior, completed)) @@ -88,7 +91,7 @@ impl QsaAttentionStage { let context = txn.cuda_context()?; admit_budget(context)?; if let Some(cache) = cache { - return decode_cached(binding, &prepared, context, cache, &k, &v, width); + return decode_cached(binding, &prepared, context, cache, SelectedKvBytes { keys: &k, values: &v, width }); } Self::decode_host(binding, &prepared, context, (&k, &v), width) } @@ -197,13 +200,11 @@ pub(super) fn decode_cached( prepared: &QsaPrepared, context: &Context<'_>, cache: &DenseWeightCache<'_>, - keys: &[u8], - values: &[u8], - width: u32, + kv: SelectedKvBytes<'_>, ) -> Result { let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; - let attended = attend_retained(context, prepared.q(), keys, values, width, failed)?; + let attended = attend_retained(context, prepared.q(), kv, failed)?; let gated = gate_retained(context, attended, prepared.gate())?; let result = project_cached_out(context, binding, prepared.weights(), &gated, cache); let cleanup = gated.close(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs index e4106476..d9d8ecc7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs @@ -41,12 +41,11 @@ type Legacy = (Box<[f32]>, Box<[f32]>, Box<[f32]>); fn original_transfer_chain( context: &Context<'_>, query: &[f32], - keys: &[u8], - values: &[u8], + kv: SelectedKvBytes<'_>, gate: &[f32], - width: u32, matrix: &DeviceBuffer<'_>, ) -> Legacy { + let SelectedKvBytes { keys, values, width } = kv; let q = upload(context, query).unwrap(); let k = upload_bytes(context, keys).unwrap(); let v = upload_bytes(context, values).unwrap(); @@ -107,9 +106,10 @@ fn prove_pair(context: &Context<'_>, matrix: &DeviceBuffer<'_>, failed: &Rc = query.iter().map(|v| v.to_bits()).collect(); let gate_bits: Vec = gate.iter().map(|v| v.to_bits()).collect(); let (keys, values) = half_kv(width as usize, zero); - let legacy = original_transfer_chain(context, &query, &keys, &values, &gate, width, matrix); + let kv = SelectedKvBytes { keys: &keys, values: &values, width }; + let legacy = original_transfer_chain(context, &query, kv, &gate, matrix); let charged = context.allocated_bytes(); - let attended = attend_retained(context, &query, &keys, &values, width, failed.clone()).unwrap(); + let attended = attend_retained(context, &query, kv, failed.clone()).unwrap(); exact(&attended.values, &legacy.0); assert_eq!(context.allocated_bytes(), charged + Q * 4); let gated = gate_retained(context, attended, &gate).unwrap(); @@ -128,6 +128,17 @@ fn prove_pair(context: &Context<'_>, matrix: &DeviceBuffer<'_>, failed: &Rc( + context: &'ctx Context<'ctx>, + query: &[f32], + keys: &[u8], + values: &[u8], + failed: &Rc>, +) -> Result> { + attend_retained(context, query, SelectedKvBytes { keys, values, width: 1 }, failed.clone()) +} + /// The finite one-cell inputs the refusal cases start from. struct RefusalInputs { query: Vec, @@ -146,14 +157,11 @@ fn prove_attend_refusals(context: &Context<'_>, failed: &Rc>, inputs: let RefusalInputs { query, keys, values, .. } = inputs; for width in [0, 2052] { assert_eq!( - attend_retained(context, query, keys, values, width, failed.clone()).err(), + attend_retained(context, query, SelectedKvBytes { keys, values, width }, failed.clone()).err(), Some(Error::InvalidDimension) ); } - assert_eq!( - attend_retained(context, &query[..Q - 1], keys, values, 1, failed.clone()).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(attend_one_cell(context, &query[..Q - 1], keys, values, failed).err(), Some(Error::InvalidDimension)); prove_finite_refusals(context, failed, inputs); } @@ -162,22 +170,19 @@ fn prove_finite_refusals(context: &Context<'_>, failed: &Rc>, inputs: let RefusalInputs { query, keys, values, .. } = inputs; let mut bad_query = query.clone(); bad_query[Q - 1] = f32::from_bits(0x7fc00001); - assert_eq!(attend_retained(context, &bad_query, keys, values, 1, failed.clone()).err(), Some(Error::NonFinite)); - assert_eq!( - attend_retained(context, query, &keys[..1022], values, 1, failed.clone()).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(attend_one_cell(context, &bad_query, keys, values, failed).err(), Some(Error::NonFinite)); + assert_eq!(attend_one_cell(context, query, &keys[..1022], values, failed).err(), Some(Error::InvalidDimension)); let mut bad_keys = keys.clone(); bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes()); - assert_eq!(attend_retained(context, query, &bad_keys, values, 1, failed.clone()).err(), Some(Error::NonFinite)); + assert_eq!(attend_one_cell(context, query, &bad_keys, values, failed).err(), Some(Error::NonFinite)); let mut bad_values = values.clone(); bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes()); - assert_eq!(attend_retained(context, query, keys, &bad_values, 1, failed.clone()).err(), Some(Error::NonFinite)); + assert_eq!(attend_one_cell(context, query, keys, &bad_values, failed).err(), Some(Error::NonFinite)); // All operands are finite, but the original F32 dot overflows. The actual // retained attention's full D2H rejects before a gate can mask the failure. + let overflowing_keys = 0x7bffu16.to_le_bytes().repeat(512); assert_eq!( - attend_retained(context, &vec![f32::MAX; Q], &0x7bffu16.to_le_bytes().repeat(512), values, 1, failed.clone()) - .err(), + attend_one_cell(context, &vec![f32::MAX; Q], &overflowing_keys, values, failed).err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), 0); @@ -190,11 +195,11 @@ fn prove_gate_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc bad_gate[Q - 1] = f32::NAN; for malformed in [&bad_gate[..], &gate[..Q - 1]] { let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension }; - let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap(); + let attended = attend_one_cell(context, query, keys, values, failed).unwrap(); assert_eq!(gate_retained(context, attended, malformed).err(), Some(expected)); assert_eq!(context.allocated_bytes(), 0); } - let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap(); + let attended = attend_one_cell(context, query, keys, values, failed).unwrap(); assert_eq!(gate_retained(foreign, attended, gate).err(), Some(Error::IdentityMismatch)); assert_eq!(context.allocated_bytes(), 0); assert_eq!(foreign.allocated_bytes(), 0); @@ -202,7 +207,7 @@ fn prove_gate_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc fn prove_out_refusals(context: &Context<'_>, foreign: &Context<'_>, failed: &Rc>, inputs: &RefusalInputs) { let RefusalInputs { query, gate, keys, values } = inputs; - let attended = attend_retained(context, query, keys, values, 1, failed.clone()).unwrap(); + let attended = attend_one_cell(context, query, keys, values, failed).unwrap(); let gated = gate_retained(context, attended, gate).unwrap(); assert_eq!(gated.buffer(foreign).err(), Some(Error::IdentityMismatch)); let malformed = upload_bytes(context, &[0; 2]).unwrap(); @@ -238,7 +243,7 @@ fn prove_sticky_failure( ) { let RefusalInputs { query, keys, values, .. } = inputs; failed.set(true); - assert_eq!(attend_retained(context, query, keys, values, 1, failed.clone()).err(), Some(Error::CudaExecution)); + assert_eq!(attend_one_cell(context, query, keys, values, failed).err(), Some(Error::CudaExecution)); assert_eq!(gated.buffer(context).err(), Some(Error::CudaExecution)); assert_eq!( super::super::qsa_index::project_out_numeric(context, &matrix, QsaMatrixKind::Bf16, &gated, failed).err(), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs index 34e9f73c..296e1259 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs @@ -230,9 +230,9 @@ impl<'ctx> QsaAttentionLease<'_, '_, 'ctx> { selected: &mut QsaSelectedCache<'_>, ) -> Result> { let prepared = self.prepared; - self.slot - .buffers - .attend_by(prepared.q(), |q, y| selected.attend(&binding.identity(), context, prepared, q, y))?; + self.slot.buffers.attend_by(prepared.q(), |query, output| { + selected.attend(&binding.identity(), context, prepared, QsaAttendBuffers { query, output }) + })?; self.slot.buffers.gate(prepared.gate())?; // Out source/cache acquisition is deliberately AFTER both finite boundaries. let output = self.project_out(binding, context, cache)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs index 9e4a8c3f..887bd046 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs @@ -11,19 +11,16 @@ fn bits(a: &[f32], b: &[f32]) { } } type Products = (Box<[f32]>, Box<[f32]>, Box<[f32]>); -#[allow(clippy::too_many_arguments)] // Literal original-first component input tuple. fn original( context: &Context<'_>, query: &[f32], - keys: &[u8], - values: &[u8], + kv: SelectedKvBytes<'_>, gate: &[f32], - width: u32, matrix: &DeviceBuffer<'_>, ) -> Result { // Exact pre-existing retained producer FIRST, including original finite boundaries. let failed = Rc::new(Cell::new(false)); - let attended = attend_retained(context, query, keys, values, width, failed.clone())?; + let attended = attend_retained(context, query, kv, failed.clone())?; let a = attended.values.clone(); let gated = gate_retained(context, attended, gate)?; let g = gated.values().to_vec().into_boxed_slice(); @@ -123,7 +120,8 @@ impl<'a, 'c> Rig<'a, 'c> { } fn prove_case(&self, case: &Case) -> usize { let (context, matrix) = (self.context, self.matrix); - let old = original(context, &case.query, &case.keys, &case.values, &case.gate, case.width, matrix).unwrap(); + let kv = SelectedKvBytes { keys: &case.keys, values: &case.values, width: case.width }; + let old = original(context, &case.query, kv, &case.gate, matrix).unwrap(); let k = upload_bytes(context, &case.keys).unwrap(); let v = upload_bytes(context, &case.values).unwrap(); let mut slot = self.buffers.borrow_mut(); @@ -162,7 +160,8 @@ impl<'a, 'c> Rig<'a, 'c> { let (query, keys, values) = (&case.query, &case.keys, &case.values); let mut bad_gate = case.gate.clone(); bad_gate[Q - 1] = invalid; - assert!(matches!(original(context, query, keys, values, &bad_gate, width, matrix), Err(Error::NonFinite))); + let kv = SelectedKvBytes { keys, values, width }; + assert!(matches!(original(context, query, kv, &bad_gate, matrix), Err(Error::NonFinite))); assert!(matches!(slot.gate(&bad_gate), Err(Error::NonFinite))); slot.reset(); } @@ -172,10 +171,8 @@ impl<'a, 'c> Rig<'a, 'c> { let (query, keys, values) = (&case.query, &case.keys, &case.values); let mut bad_query = query.clone(); bad_query[Q - 1] = invalid; - assert!(matches!( - original(context, &bad_query, keys, values, &case.gate, width, matrix), - Err(Error::NonFinite) - )); + let kv = SelectedKvBytes { keys, values, width }; + assert!(matches!(original(context, &bad_query, kv, &case.gate, matrix), Err(Error::NonFinite))); assert!(matches!( slot.attend_by(&bad_query, |_, _| panic!("query must refuse before CUDA callback")), Err(Error::NonFinite) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs index ae8274f5..836b2cdf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs @@ -5,12 +5,12 @@ use super::{ dense_weight_cache::{DenseWeightCache, QsaResident}, gr::ResidualReady, qsa_index::{QsaPrior, driver_error, project, validate_values}, + qsa_prompt_index::PromptIndexDevices, session::QwenStepTxn, }; use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights}; use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeBatchWorkspace, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix, - QsaPromptIndexWorkspace, QsaPromptSelection, + Context, DeviceBuffer, QsaChunkRows, QsaIndexPrior, QsaPromptIndexPrefix, QsaPromptSelection, }; use std::rc::Rc; fn driver(error: leleka_cuda_driver::Error) -> Error { @@ -19,6 +19,13 @@ fn driver(error: leleka_cuda_driver::Error) -> Error { other => driver_error(other), } } +/// The model binding, dense weight cache and step transaction a decode index is built and checked against. +#[derive(Clone, Copy)] +pub(super) struct DecodeStepOwners<'a, 'ctx, 'session, 'driver> { + pub(super) binding: &'a ModelBinding, + pub(super) cache: &'a DenseWeightCache<'ctx>, + pub(super) txn: &'a QwenStepTxn<'session, 'driver>, +} pub(super) struct QsaDecodeIndex<'source, 'lease, 'ctx> { binding: BindingIdentity, context: &'ctx Context<'ctx>, @@ -31,24 +38,21 @@ pub(super) struct QsaDecodeIndex<'source, 'lease, 'ctx> { selected: QsaPromptSelection<'lease, 'ctx>, } impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { - #[allow(clippy::too_many_arguments)] // Actual current transaction, immutable prior and two model owners. pub(super) fn prepare( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, + owners: DecodeStepOwners<'_, 'ctx, '_, '_>, layer: LayerId, input: &'source ResidualReady, prior: &QsaPrior, - owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: PromptIndexDevices<'lease, '_, 'ctx>, ) -> Result { + let DecodeStepOwners { binding, cache, txn } = owners; Self::admit_step(binding, txn, layer, input, prior)?; let context = cache.retained_context(binding, txn.cuda_context()?)?; let entry = Self::checked_entry(cache, binding, layer)?; let txn_owner = txn.residual_handoff_owner()?; let rows = DecodeRows::project(context, binding, entry, input, cache)?; let gate = rows.gate()?; - let selected = Self::select(owner, workspace, (txn, prior), cache, entry, &rows)?; + let selected = Self::select(devices, (txn, prior), cache, entry, &rows)?; let result = Self { binding: binding.identity(), context, @@ -106,13 +110,13 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { } /// The index append and the block selection of the step's position on the prompt index workspace. fn select( - owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: PromptIndexDevices<'lease, '_, 'ctx>, (txn, prior): (&QwenStepTxn<'_, '_>, &QsaPrior), cache: &DenseWeightCache<'ctx>, entry: &QsaResident, rows: &DecodeRows, ) -> Result> { + let PromptIndexDevices { owner, workspace } = devices; let (pooled, tail, dead) = prior.native_index_image()?; let p = u32::try_from(txn.position().get()).map_err(|_| Error::InvalidPosition)?; let gamma = cache.qsa_norms(entry)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs index 2d316150..42761c43 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs @@ -18,7 +18,7 @@ mod index_resident; pub(super) use index_resident::QsaIndexKeyCache; #[path = "qsa_selected_cache.rs"] mod selected_cache; -pub(super) use selected_cache::QsaSelectedCache; +pub(super) use selected_cache::{QsaAttendBuffers, QsaSelectedCache}; #[path = "qsa_input_scratch.rs"] mod input_scratch; pub(super) use input_scratch::{QsaInputLease, QsaInputScratch}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs index ed6c01df..55825f9c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs @@ -2,12 +2,14 @@ //! snapshots/index prefixes are the actual completed driver products; no host //! residual or query/selection certificate is fabricated. use super::super::dense_weight_cache::QsaResident; +use super::super::qsa_attention::PromptDevices; +use super::super::qsa_prompt_index::PromptChunkOwners; use super::super::session::{TargetStepOrigin, chunk::QwenChunkTxn}; use super::*; use leleka_cuda_driver::{ CompletedQsaKvAppend, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaChunkPrior, QsaIndexPrior, QsaKvAppendTarget, QsaNativeKind, - QsaNativeWeight, QsaPromptAttention, QsaPromptIndexState, QsaPromptKv, QsaPromptStage, + QsaNativeWeight, QsaPromptIndexState, QsaPromptKv, }; const ROLES: [QsaMatrixRole; 6] = [ QsaMatrixRole::K, @@ -223,17 +225,13 @@ impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; Ok((context, out, kind)) } - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn complete( self, - model: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &QwenChunkTxn<'_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - kv: &mut QsaPromptKv<'ctx>, - stage: &mut QsaPromptStage<'ctx>, - attention: &mut QsaPromptAttention<'ctx>, + owners: PromptChunkOwners<'_, 'ctx, '_, '_>, + devices: PromptDevices<'_, 'ctx>, ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, PromptDeviceQsaState<'ctx>)> { + let PromptChunkOwners { binding: model, cache, chunk } = owners; + let PromptDevices { kv, stage, attention, workspace } = devices; let (ctx, out, kind) = self.check_inputs(model, cache, chunk)?; let Self { binding, origin, context, layer, prior, provider, identities, selected } = self; let snapshot = prior.native_snapshot(kv)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs index 5aa0b7ef..d999648f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs @@ -24,6 +24,18 @@ fn driver(e: leleka_cuda_driver::Error) -> Error { other => super::qsa_index::driver_error(other), } } +/// The model binding, dense weight cache and chunk transaction a prompt chunk's QSA batch is built and checked against. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PromptChunkOwners<'a, 'ctx, 'session, 'driver> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) chunk: &'a QwenChunkTxn<'session, 'driver>, +} +/// The index workspace a batch leases and the native batch workspace its append and select run on. +pub(in crate::qwen_forward) struct PromptIndexDevices<'lease, 'a, 'ctx> { + pub(in crate::qwen_forward) owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, + pub(in crate::qwen_forward) workspace: &'a mut NativeBatchWorkspace<'ctx>, +} pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> { binding: BindingIdentity, origin: TargetStepOrigin, @@ -37,6 +49,7 @@ pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> { } /// Host images of one prompt chunk, filled row by row from the native projections. struct PromptHost { + rows: usize, raw: Vec, k: Vec, v: Vec, @@ -46,8 +59,15 @@ struct PromptHost { } impl PromptHost { fn reserve(t: usize) -> Result { - let mut host = - Self { raw: Vec::new(), k: Vec::new(), v: Vec::new(), qfull: Vec::new(), iq: Vec::new(), gate: Vec::new() }; + let mut host = Self { + rows: t, + raw: Vec::new(), + k: Vec::new(), + v: Vec::new(), + qfull: Vec::new(), + iq: Vec::new(), + gate: Vec::new(), + }; for (x, n) in [ (&mut host.raw, t * 128), (&mut host.k, t * 512), @@ -94,15 +114,16 @@ impl PromptHost { } Ok(()) } + /// Appends and selects the chunk that starts at the prior's next position. fn append_select<'lease, 'ctx>( &self, - owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: PromptIndexDevices<'lease, '_, 'ctx>, cache: &DenseWeightCache<'ctx>, entry: &QsaResident, prior: &QsaPrior, - (first, t): (u64, usize), ) -> Result> { + let PromptIndexDevices { owner, workspace } = devices; + let (first, t) = (prior.next_position(), self.rows); let (pooled, tail, dead) = prior.native_index_image()?; let gamma = cache.qsa_norms(entry)?; let prior = QsaIndexPrior { pooled: &pooled, tail: &tail, dead: &dead }; @@ -202,21 +223,18 @@ fn gather_prompt<'source, 'ctx>( host.validate(t)?; Ok((sources, host)) } -#[allow(clippy::too_many_arguments)] // Actual whole chunk/current prior and admitted fixed owners. pub(super) fn prepare<'source, 'lease, 'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &QwenChunkTxn<'_, '_>, + owners: PromptChunkOwners<'_, 'ctx, '_, '_>, layer: LayerId, prior: &QsaPrior, rows: &mut [NativeProjectionRow<'source, 'ctx>], - owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: PromptIndexDevices<'lease, '_, 'ctx>, ) -> Result> { + let PromptChunkOwners { binding, cache, chunk } = owners; let (context, entry, origin, first) = - index_guards(binding, cache, chunk, (layer, prior), (rows, owner.capacity()))?; + index_guards(binding, cache, chunk, (layer, prior), (rows, devices.owner.capacity()))?; let (sources, host) = gather_prompt(rows, binding, cache, chunk, (layer, first))?; - let selected = host.append_select(owner, workspace, cache, entry, prior, (first, rows.len()))?; + let selected = host.append_select(devices, cache, entry, prior)?; chunk.validate_prompt_qsa_prior(layer, prior)?; cache.retained_context(binding, context)?; origin.validate(chunk.original_session()?)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs index 3656c251..703dac4d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs @@ -153,6 +153,12 @@ fn install_misses( Ok(Plan { next, misses, k, v, selected }) } +/// The uploaded query a selected-cache attend pass reads and the output buffer it writes. +pub(in crate::qwen_forward) struct QsaAttendBuffers<'a, 'ctx> { + pub(in crate::qwen_forward) query: &'a DeviceBuffer<'ctx>, + pub(in crate::qwen_forward) output: &'a mut DeviceBuffer<'ctx>, +} + pub(in crate::qwen_forward) struct QsaSelectedCache<'ctx> { binding: BindingIdentity, context: &'ctx Context<'ctx>, @@ -252,9 +258,9 @@ impl<'ctx> QsaSelectedCache<'ctx> { binding: &BindingIdentity, context: &Context<'_>, prepared: &QsaPrepared, - query: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, + buffers: QsaAttendBuffers<'_, '_>, ) -> Result<()> { + let QsaAttendBuffers { query, output } = buffers; let (layer, slot) = self.admit_attend(binding, context, prepared)?; let plan = plan(&self.layers[slot], &prepared.candidate, &prepared.ids)?; let workspace = self.workspace.as_mut().ok_or(Error::CudaExecution)?;