diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 4012bba5..92afeeda 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -171,7 +171,8 @@ fn load_moe<'ctx>( ); if !super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) { operator_note( - "footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)", + "footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from \ + the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)", ); } Ok(moe) @@ -241,7 +242,8 @@ pub(super) fn share_rt_dense_roles<'ctx>( if let Some(retained) = executor.retained_mtp_weights() { let share = moe.share_rt_mtp_dense(retained).map_err(at("share_rt_mtp_dense"))?; operator_note(&format!( - "footprint: MTP dense roles shared with the RT bank (byte-equal): {} shared, {} kept ({} differing), {:.1} MiB released", + "footprint: MTP dense roles shared with the RT bank (byte-equal): {} shared, {} kept ({} differing), \ + {:.1} MiB released", share.shared, share.kept, share.differing, @@ -285,7 +287,8 @@ pub(super) fn open_prefix(config: &StackConfig) -> Option, bytes: u64, available: Option) { operator_note(&format!( - "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, \ + host memory available {:?} MiB, namespace {}", serve.block_tokens(), bytes >> 20, PARKED_STATE_ESTIMATE >> 20, @@ -328,7 +331,8 @@ pub(super) fn open_expert_cache<'ctx>( fn note_expert_cache(cache: &OriginalExpertCache<'_>, filled: usize, loan: Option) { operator_note(&format!( - "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", + "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; \ + GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", cache.slots(), cache.bytes() as f64 / f64::from(1u32 << 30), if cache.per_layer_admission() { "per layer" } else { "global" }, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs index 4760c748..92b0e638 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs @@ -47,13 +47,16 @@ fn forward_outcome

(pending: Result

, cancel: &mut dyn FnMut() -> bool) -> s } } /// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. -/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). +/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room +/// goes). pub(super) fn vram_note(context: &Context<'_>, label: &str) { - // LELEKA_VRAM_LEDGER=1: the device allocations that appeared since the previous note, per call site (nothing when off) + // LELEKA_VRAM_LEDGER=1: the device allocations that appeared since the previous note, per call site (nothing when + // off) leleka_cuda_driver::vram_ledger::report(label); if profile::enabled() { if let Ok((free, total)) = context.memory_info() { - // the low-water mark of the card's free VRAM over every note of this process: the number the reserve must cover + // the low-water mark of the card's free VRAM over every note of this process: the number the reserve must + // cover static LOWEST_FREE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX); let lowest = LOWEST_FREE.fetch_min(free, std::sync::atomic::Ordering::Relaxed).min(free); eprintln!( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs index 4e503d1b..6ab34691 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs @@ -74,7 +74,8 @@ fn trace_adaptive(round: &RoundFacts, c: &Choice, ms: f64, drafts_after: usize, } let plan = pol.draft_plan(); eprintln!( - "DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2} bar={:.3} slope={:.2}", + "DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} \ + next_plan={}/{:.2} bar={:.3} slope={:.2}", round.round_number, round.t, c.origin, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs index 5ef18571..0ba83ce4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs @@ -164,6 +164,17 @@ impl OriginalSpecController { Ok(plan) } + fn shrink_window(plan: &mut WindowPlan, room: i64) { + if (plan.t as i64) > room { + // A shrunk window is not the policy's offer: its observation would teach the wrong width. + plan.t = room as usize; + plan.choice = None; + if plan.t == 1 { + plan.lookup = false; + } + } + } + /// Rows p .. p+t-1 each need a cell: past `max_context` there is none. Upstream 41cf05a0 (`e85567b6`, generate.cpp /// `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, /// `max_new` @@ -178,14 +189,7 @@ impl OriginalSpecController { self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished = true; return Ok(false); } - if (plan.t as i64) > room { - // A shrunk window is not the policy's offer: its observation would teach the wrong width. - plan.t = room as usize; - plan.choice = None; - if plan.t == 1 { - plan.lookup = false; - } - } + Self::shrink_window(plan, room); if r.consumed.len().checked_add(plan.t).ok_or(Error::Overflow)? > r.consumed.capacity() { return Err(Error::InputAllocation.into()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs index e3e2fef2..c8819551 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs @@ -201,6 +201,14 @@ pub(crate) struct PrefillRecords { impl PrefillRecords { pub(crate) fn new(next_tokens: &[i32], cell0: i64, vocabulary: u32) -> Result { let n = next_tokens.len(); + Self::check_geometry(n, cell0, vocabulary)?; + if next_tokens.iter().any(|&v| v < 0 || v as u32 >= vocabulary) { + return Err(Error::InvalidToken); + } + let rec = Self::build_records(next_tokens, cell0)?; + Ok(Self { records: rec.into_boxed_slice(), rows: n, cell0 }) + } + fn check_geometry(n: usize, cell0: i64, vocabulary: u32) -> Result<()> { if n == 0 || (n as i64) > (crate::qwen_forward::contract::serving_cells() as i64) || cell0 < 0 @@ -212,22 +220,27 @@ impl PrefillRecords { { return Err(Error::InvalidDimension); } - if next_tokens.iter().any(|&v| v < 0 || v as u32 >= vocabulary) { - return Err(Error::InvalidToken); - } + Ok(()) + } + fn build_records(next_tokens: &[i32], cell0: i64) -> Result> { + let n = next_tokens.len(); let count = n.checked_mul(29).ok_or(Error::Overflow)?; let mut rec = Vec::new(); rec.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; rec.resize(count, 0); rec[..n].copy_from_slice(next_tokens); for i in 0..n { - let cell = i32::try_from(cell0.checked_add(i as i64).ok_or(Error::Overflow)?) - .map_err(|_| Error::InvalidPosition)?; - let next = cell.checked_add(1).ok_or(Error::Overflow)?; - rec[n + i * 4..n + (i + 1) * 4].copy_from_slice(&[cell, next, next / 4, next]); - rec[5 * n + i * 24..5 * n + (i + 1) * 24].fill(cell); + Self::fill_row(&mut rec, n, i, cell0)?; } - Ok(Self { records: rec.into_boxed_slice(), rows: n, cell0 }) + Ok(rec) + } + fn fill_row(rec: &mut [i32], n: usize, i: usize, cell0: i64) -> Result<()> { + let cell = + i32::try_from(cell0.checked_add(i as i64).ok_or(Error::Overflow)?).map_err(|_| Error::InvalidPosition)?; + let next = cell.checked_add(1).ok_or(Error::Overflow)?; + rec[n + i * 4..n + (i + 1) * 4].copy_from_slice(&[cell, next, next / 4, next]); + rec[5 * n + i * 24..5 * n + (i + 1) * 24].fill(cell); + Ok(()) } pub(crate) fn tokens(&self) -> &[i32] { &self.records[..self.rows] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs index 9ca3c774..6c3bbfbd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs @@ -51,13 +51,27 @@ impl OriginalPromptSample { txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, ) -> Result<()> { txn.validate_final(completed)?; - if !self.binding.matches(&binding.identity()) - || !self.phase.same(&txn.phase()) - || self.token != completed.token() - || self.position != completed.position() - { + if !self.matches_final(binding, completed, txn) { return Err(Error::IdentityMismatch); } + self.check_known_next(completed, txn) + } + fn matches_final( + &self, + binding: &ModelBinding, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + ) -> bool { + self.binding.matches(&binding.identity()) + && self.phase.same(&txn.phase()) + && self.token == completed.token() + && self.position == completed.position() + } + fn check_known_next( + &self, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + ) -> Result<()> { if self.conditioning { if txn.known_prompt_next() != Ok(Some(self.next)) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs index c5adf9e7..0d2d45f2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs @@ -17,15 +17,35 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } - let mixed = GrStage::final_mix_original_prompt(binding, completed, txn, cache)?; - if mixed.len() != EMBEDDING || mixed.iter().any(|value| !value.is_finite()) { - return Err(Error::NonFinite); - } + let mixed = Self::finite_final_mix(binding, completed, txn, cache)?; if self.sampler_wants(completed.position())? { return Err(Error::Unsupported(Stage::Output)); } let logits = self.project_mixed(binding.identity(), completed.token(), completed.position(), &mixed, context, false)?; + self.certify_prompt_logits(binding, completed, txn, logits) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn finite_final_mix( + binding: &ModelBinding, + completed: &super::super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + cache: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + ) -> Result> { + let mixed = GrStage::final_mix_original_prompt(binding, completed, txn, cache)?; + if mixed.len() != EMBEDDING || mixed.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + Ok(mixed) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn certify_prompt_logits( + &self, + binding: &ModelBinding, + completed: &super::super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + logits: FiniteLogits, + ) -> Result { txn.validate_final(completed)?; logits.validate_for(&binding.identity(), completed.token(), completed.position())?; if matches!(&logits.values, LogitValues::Compact(_)) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs index 65990f47..b418c058 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs @@ -41,6 +41,10 @@ impl OutputStage<'_, '_> { if !self.reset_replay_record.get() { return Ok(()); } + self.store_replay_logits(logits, values) + } + + fn store_replay_logits(&self, logits: &FiniteLogits, values: &[FiniteF32]) -> Result<()> { if !self.binding.matches(&logits.binding) || values.len() != VOCABULARY { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs index 54087382..3aaf554c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs @@ -162,12 +162,16 @@ impl<'ctx> OriginalNativeOutput<'ctx> { let selected = graph.native_head_after_launch(stream, sampling).map_err(driver)?; self.validate(binding, self.context)?; authenticate()?; - if selected.position() != sampling.position + self.check_selected(&selected, sampling.position)?; + Ok(selected) + } + fn check_selected(&self, selected: &NativeHeadSelection, position: u64) -> Result<()> { + if selected.position() != position || selected.vocabulary() != self.head.as_ref().ok_or(Error::IdentityMismatch)?.vocabulary() { return Err(Error::IdentityMismatch); } - Ok(selected) + Ok(()) } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { let embed = self.embed.take().map_or(Ok(()), |e| e.close().map_err(driver)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs index a0b756eb..2f5a1ee2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs @@ -132,16 +132,9 @@ fn conv_history( let context = transport.context; let conv = transport.allocate(PLE_HC * 4)?; let next = transport.allocate(PLE_HISTORY * 4)?; - let (inputs, outputs) = transport.buffers.split_at_mut(conv); - let (conv_output, next_output) = outputs.split_at_mut(1); + let operands = conv_operands(&mut transport.buffers, conv, prior, normalized_index)?; let result = context - .ple_conv_history_f32( - at(inputs, prior)?, - at(inputs, normalized_index)?, - conv_weights, - conv_output[0].as_mut().ok_or(Error::IdentityMismatch)?, - next_output[0].as_mut().ok_or(Error::IdentityMismatch)?, - ) + .ple_conv_history_f32(operands.prior, operands.normalized, conv_weights, operands.conv, operands.next) .map_err(ple_driver_error); transport.note(&result); result?; @@ -151,6 +144,30 @@ fn conv_history( Ok((conv_index, next)) } +/// The four buffers of the conv-and-history kernel: two inputs read, two outputs written. +struct ConvOperands<'a, 'ctx> { + prior: &'a DeviceBuffer<'ctx>, + normalized: &'a DeviceBuffer<'ctx>, + conv: &'a mut DeviceBuffer<'ctx>, + next: &'a mut DeviceBuffer<'ctx>, +} + +fn conv_operands<'a, 'ctx>( + buffers: &'a mut [Option>], + conv: usize, + prior: usize, + normalized_index: usize, +) -> Result> { + let (inputs, outputs) = buffers.split_at_mut(conv); + let (conv_output, next_output) = outputs.split_at_mut(1); + Ok(ConvOperands { + prior: at(inputs, prior)?, + normalized: at(inputs, normalized_index)?, + conv: conv_output[0].as_mut().ok_or(Error::IdentityMismatch)?, + next: next_output[0].as_mut().ok_or(Error::IdentityMismatch)?, + }) +} + #[cfg(test)] #[allow(clippy::too_many_arguments)] pub(super) fn compose_observed( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prefetch_policy.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prefetch_policy.rs index 70dded92..ca395285 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prefetch_policy.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prefetch_policy.rs @@ -97,7 +97,8 @@ impl PrefetchPolicy { return None; } Some(format!( - "leleka-serve cpu expert pool: page-touch pass {} (groups {}; ms per expert: pass {:.3} over {} groups, skip {:.3} over {})", + "leleka-serve cpu expert pool: page-touch pass {} (groups {}; ms per expert: pass {:.3} over {} groups, \ + skip {:.3} over {})", if self.preferred == PASS { "preferred" } else { "skipped" }, self.groups, self.cost[PASS], diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs index 13e30ba2..e5fd266a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs @@ -92,36 +92,37 @@ const STAGES: [Stage; 26] = [ Stage::Publish, Stage::Lend, ]; +const STAGE_NAMES: [(Stage, &str); 26] = [ + (Stage::Input, "input"), + (Stage::InputEmbedding, "input.embedding"), + (Stage::InputPle, "input.ple"), + (Stage::Initialize, "init"), + (Stage::InitSources, "init.sources"), + (Stage::InitUpload, "init.upload"), + (Stage::Ple, "ple"), + (Stage::Validate, "validate"), + (Stage::AttnRead, "attn_read"), + (Stage::Gdn, "gdn"), + (Stage::GdnStateIn, "gdn.state_in"), + (Stage::GdnCompute, "gdn.compute"), + (Stage::GdnStateOut, "gdn.state_out"), + (Stage::Qsa, "qsa"), + (Stage::FfnRead, "ffn_read"), + (Stage::Moe, "moe"), + (Stage::MoePrepare, "moe.prepare"), + (Stage::MoeSpans, "moe.spans"), + (Stage::MoeRing, "moe.ring"), + (Stage::MoeFinish, "moe.finish"), + (Stage::Inject, "inject"), + (Stage::Final, "final"), + (Stage::DraftKv, "draft_kv"), + (Stage::FinishPreview, "finish_preview"), + (Stage::Publish, "publish"), + (Stage::Lend, "lend"), +]; impl Stage { fn name(self) -> &'static str { - match self { - Self::Input => "input", - Self::InputEmbedding => "input.embedding", - Self::InputPle => "input.ple", - Self::Initialize => "init", - Self::InitSources => "init.sources", - Self::InitUpload => "init.upload", - Self::Ple => "ple", - Self::Validate => "validate", - Self::AttnRead => "attn_read", - Self::Gdn => "gdn", - Self::GdnStateIn => "gdn.state_in", - Self::GdnCompute => "gdn.compute", - Self::GdnStateOut => "gdn.state_out", - Self::Qsa => "qsa", - Self::FfnRead => "ffn_read", - Self::Moe => "moe", - Self::MoePrepare => "moe.prepare", - Self::MoeSpans => "moe.spans", - Self::MoeRing => "moe.ring", - Self::MoeFinish => "moe.finish", - Self::Inject => "inject", - Self::Final => "final", - Self::DraftKv => "draft_kv", - Self::FinishPreview => "finish_preview", - Self::Publish => "publish", - Self::Lend => "lend", - } + STAGE_NAMES.iter().find(|(stage, _)| *stage == self).map_or("input", |&(_, name)| name) } fn index(self) -> usize { STAGES.iter().position(|s| *s == self).unwrap_or(0) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs index 03796fa6..db530eb8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs @@ -1,6 +1,6 @@ //! Moved out of the parent module by STRA-338: impl PromptDeviceRead. -use super::produce_original_gdn_fn::{GdnLayer, Lap, QsaLayerDevices, inject_span, produce_block}; +use super::produce_original_gdn_fn::{DeviceBlockResult, GdnLayer, Lap, QsaLayerDevices, inject_span, produce_block}; #[allow(unused_imports)] use super::*; @@ -30,7 +30,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx pub(in crate::qwen_forward) fn device(&self) -> &OriginalDeviceGrRead<'arena, 'loan, 'ctx> { &self.device } - /// The attention layer these rows are at (the producer's layer id) and the context, in the phase `same_phase` accepts. + /// The attention layer these rows are at (the producer's layer id) and the context, in the phase `same_phase` + /// accepts. fn attention_layer( &self, same_phase: impl FnOnce(&OriginalPromptPhase) -> bool, @@ -166,7 +167,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx cache: &DenseWeightCache<'ctx>, producer: &mut OriginalPromptDevice<'ctx>, next_role: GrRole, - produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> DeviceBlockResult<'arena, 'loan, 'ctx>, ) -> Result> { self.check_next_role(binding, cache, next_role)?; let block = produce_block(self.device, produce)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs index 99823665..61d8d6c4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs @@ -303,7 +303,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx cache: &'weight DenseWeightCache<'ctx>, producer: &mut OriginalPromptDevice<'ctx>, next_role: GrRole, - produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> DeviceBlockResult<'arena, 'loan, 'ctx>, ) -> Result> { self.check_normed_step(binding, cache, next_role)?; let (gamma, epsilon) = normed_gamma(binding, cache, next_role)?; @@ -363,11 +363,14 @@ fn normed_gamma<'w, 'ctx>( Ok((gamma, resident.weights.epsilon())) } +/// What a block producer returns: the block of the device read's lease. +pub(super) type DeviceBlockResult<'arena, 'loan, 'ctx> = Result>; + /// The producer consumes the device read and must return a block of the very same lease. pub(super) fn produce_block<'arena, 'loan, 'ctx>( device: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, -) -> Result> { + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> DeviceBlockResult<'arena, 'loan, 'ctx>, +) -> DeviceBlockResult<'arena, 'loan, 'ctx> { let identity = device.lease_identity(); let block = produce(device)?; if !identity.same_lease(&block.lease_identity()) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs index 18fa447a..a31370c0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::NativeBatchWorkspace; impl<'ctx> PromptPleHistory<'ctx> { pub(in super::super) fn from_prior( @@ -63,7 +64,7 @@ pub(super) fn run_transfer<'ctx, T>( context: &Context<'_>, producer: &mut OriginalPromptDevice<'ctx>, span: impl Sized, - transfer: impl FnOnce(&mut OriginalPromptDevice<'ctx>, &mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>) -> Result, + transfer: impl FnOnce(&mut OriginalPromptDevice<'ctx>, &mut NativeBatchWorkspace<'ctx>) -> Result, ) -> Result { let result = (|| { let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs index 2b5e2504..87c39f63 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs @@ -25,13 +25,17 @@ impl<'source, 'ctx> PromptDeviceSource<'source, 'ctx> { if !std::ptr::eq(context, txn.cuda_context()?) || !std::ptr::eq(txn.input()?.as_ref(), input) { return Err(Error::IdentityMismatch); } + Self::check_input_values(input)?; + Ok(Self { binding: binding.identity(), context, input: SourceInput::Borrowed(input), original: None }) + } + fn check_input_values(input: &InputReady) -> Result<()> { if input.streams().values().len() != 10240 || input.ple_embedding().len() != 2560 { return Err(Error::InvalidDimension); } if input.streams().values().iter().chain(input.ple_embedding()).any(|x| !x.is_finite()) { return Err(Error::NonFinite); } - Ok(Self { binding: binding.identity(), context, input: SourceInput::Borrowed(input), original: None }) + Ok(()) } pub(in crate::qwen_forward) fn from_original( binding: &ModelBinding, @@ -206,13 +210,16 @@ impl Sources<'_, '_> { txn.validate_binding(&self.binding)?; let s = self.rows.get(index).ok_or(Error::IdentityMismatch)?; txn.validate_input(s.input.token(), s.input.position())?; - let layer = match role { - GrRole::Attention(l) | GrRole::Ffn(l) => l, - GrRole::Final => return Err(Error::IdentityMismatch), - }; - let layer = LayerId::new(u64::from(layer), Dimension::new(u64::from(binding.layer_count()))?)?; + let layer = Self::role_layer(binding, role)?; let identity = TokenLayer::new(s.input.token(), s.input.position(), layer); identity.validate(txn.token(), txn.position(), layer)?; Ok(identity) } + fn role_layer(binding: &ModelBinding, role: GrRole) -> Result { + let layer = match role { + GrRole::Attention(l) | GrRole::Ffn(l) => l, + GrRole::Final => return Err(Error::IdentityMismatch), + }; + LayerId::new(u64::from(layer), Dimension::new(u64::from(binding.layer_count()))?) + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/impl_role.rs index b2954398..e4513bbb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/impl_role.rs @@ -65,7 +65,7 @@ impl<'ctx> ProjectionRow<'_, 'ctx> { input: &ResidualReady, role: Role, ) -> Result<()> { - self.check_identity(binding, cache, txn, layer, input, role)?; + self.check_identity(binding, cache, txn, input, (layer, role))?; self.check_provider(binding, cache, layer, role)?; self.check_row(role) } @@ -74,26 +74,33 @@ impl<'ctx> ProjectionRow<'_, 'ctx> { binding: &ModelBinding, cache: &DenseWeightCache<'_>, txn: &QwenStepTxn<'_, '_>, - layer: LayerId, input: &ResidualReady, - role: Role, + key: (LayerId, Role), ) -> Result<()> { txn.validate_projection_branch(&self.origin)?; txn.validate_input(input.identity().token(), input.identity().position())?; let context = txn.cuda_context()?; cache.retained_context(binding, context)?; - if !self.binding.matches(&binding.identity()) - || !std::ptr::eq(self.context, context) - || self.layer != layer - || self.role != role - || !std::ptr::eq(self.source, input) - || self.source.identity() != input.identity() - { + if !self.same_row(binding, context, input, key) { return Err(Error::IdentityMismatch); } - input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + input.validate_origin(&binding.identity(), GrRole::Attention(key.0.get()))?; Ok(()) } + fn same_row( + &self, + binding: &ModelBinding, + context: &Context<'_>, + input: &ResidualReady, + (layer, role): (LayerId, Role), + ) -> bool { + self.binding.matches(&binding.identity()) + && std::ptr::eq(self.context, context) + && self.layer == layer + && self.role == role + && std::ptr::eq(self.source, input) + && self.source.identity() == input.identity() + } fn check_provider( &self, binding: &ModelBinding, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs index 3f322a9d..a7d6b56b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs @@ -84,7 +84,8 @@ impl<'ctx> Q6Job<'_, 'ctx> { #[cfg(test)] if let Err(error) = &operation { eprintln!( - "PUBLIC CUDA stage={driver_stage} rows={} columns={} allocated={} budget={} shared_failed={} context_poisoned={} error={error:?}", + "PUBLIC CUDA stage={driver_stage} rows={} columns={} allocated={} budget={} shared_failed={} \ + context_poisoned={} error={error:?}", self.rows, self.tokens, self.context.allocated_bytes(), 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 2608a035..a3f3ba48 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 @@ -70,6 +70,20 @@ struct AttendBuffers<'ctx> { y: Option>, } impl<'ctx> AttendBuffers<'ctx> { + /// Query, keys and values uploaded, then the output allocated. + fn upload( + &mut self, + context: &'ctx Context<'ctx>, + query: &[f32], + (keys, values): (&[u8], &[u8]), + failed: &Cell, + ) -> Result<()> { + self.q = Some(upload_retained_f32(context, query, failed)?); + self.k = Some(upload_retained_bytes(context, keys, failed)?); + self.v = Some(upload_retained_bytes(context, values, failed)?); + self.y = Some(allocate(context, Q)?); + Ok(()) + } fn launch( &mut self, context: &'ctx Context<'ctx>, @@ -78,10 +92,7 @@ impl<'ctx> AttendBuffers<'ctx> { width: u32, failed: &Cell, ) -> Result> { - self.q = Some(upload_retained_f32(context, query, failed)?); - self.k = Some(upload_retained_bytes(context, keys, failed)?); - self.v = Some(upload_retained_bytes(context, values, failed)?); - self.y = Some(allocate(context, Q)?); + 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) = (q.ok_or(Error::CudaExecution)?, k.ok_or(Error::CudaExecution)?, v.ok_or(Error::CudaExecution)?); @@ -138,12 +149,12 @@ pub(super) fn gate_retained<'ctx>( let read = settle_retained(result, cleanup, &mut gated, &attended.failed)?; Ok(QsaGated { context, buffer: gated, values: read, failed: attended.failed }) } -fn launch_gate<'ctx>( +/// The attended row is this context's own, healthy and finite, with a full output buffer: that buffer. +fn check_gate_inputs<'a, 'ctx>( context: &'ctx Context<'ctx>, - attended: &QsaAttended<'ctx>, + attended: &'a QsaAttended<'ctx>, gate_values: &[f32], - (gate, gated): (&mut Option>, &mut Option>), -) -> Result> { +) -> Result<&'a DeviceBuffer<'ctx>> { if !std::ptr::eq(context, attended.context) { return Err(Error::IdentityMismatch); } @@ -156,6 +167,15 @@ fn launch_gate<'ctx>( if actual.len() != Q * 4 { return Err(Error::InvalidDimension); } + Ok(actual) +} +fn launch_gate<'ctx>( + context: &'ctx Context<'ctx>, + attended: &QsaAttended<'ctx>, + gate_values: &[f32], + (gate, gated): (&mut Option>, &mut Option>), +) -> Result> { + let actual = check_gate_inputs(context, attended, gate_values)?; *gate = Some(upload_retained_f32(context, gate_values, &attended.failed)?); *gated = Some(allocate(context, Q)?); let (gate_buffer, output) = 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 b07e73c9..06cb785e 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 @@ -30,8 +30,7 @@ impl NativeAttended<'_, '_> { self.origin.validate_projection_branch(chunk.original_session()?)?; chunk.validate_prepared_attention_input(proof, self.source)?; cache.retained_context(binding, context)?; - let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; - self.identity.validate(token, pos, layer)?; + self.check_prompt_identity(chunk, local, layer)?; let entry = cache.qsa(binding, layer.get())?; if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) @@ -39,6 +38,20 @@ impl NativeAttended<'_, '_> { { return Err(Error::IdentityMismatch); } + self.validate_source_values(binding, layer) + } + /// The identity of the prompt row `local` of the chunk, checked against this attended row. + fn check_prompt_identity( + &self, + chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>, + local: usize, + layer: LayerId, + ) -> Result<()> { + let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; + self.identity.validate(token, pos, layer) + } + /// The source row belongs to the attention layer, and the attended values and the gate are finite. + fn validate_source_values(&self, binding: &ModelBinding, layer: LayerId) -> Result<()> { self.source.validate_origin( &binding.identity(), crate::model_binding::qwen4exp_input::GrRole::Attention(layer.get()), @@ -95,8 +108,7 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { attention: &mut leleka_cuda_driver::QsaPromptAttention<'ctx>, workspace: &mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>, ) -> Result { - let context = cache.retained_context(binding, chunk.context()?)?; - let origin = chunk.original_session()?.target_origin()?; + let (context, origin) = Self::owner(binding, cache, chunk)?; chunk.validate_prompt_qsa_prior(layer, prior)?; let snapshot = prior.native_snapshot(kv)?.clone(); let t = index.rows(); @@ -108,6 +120,16 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { let provider = cache.qsa(binding, layer.get())?.weights.clone(); Ok(Self { index, append, values, binding: binding.identity(), layer, context, origin, provider }) } + /// The context the cache retains for the chunk, and the origin of the chunk's target step. + fn owner( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &super::super::session::chunk::QwenChunkTxn<'_, '_>, + ) -> Result<(&'ctx Context<'ctx>, super::super::session::TargetStepOrigin)> { + let context = cache.retained_context(binding, chunk.context()?)?; + let origin = chunk.original_session()?.target_origin()?; + Ok((context, origin)) + } /// This is the genuine causal row callback, never a batch-final relabel. pub(in super::super) fn publish_row( &self, @@ -140,17 +162,25 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { txn.validate_projection_branch(&self.origin)?; let context = cache.retained_context(binding, txn.cuda_context()?)?; let local = self.local_index(txn)?; - if !self.binding.matches(&binding.identity()) - || layer != self.layer - || !std::ptr::eq(context, self.context) - || !std::ptr::eq(input, self.index.source(local)?) - || !Rc::ptr_eq(&self.provider, &cache.qsa(binding, layer.get())?.weights) - { + if !self.owns_context(binding, layer, context) || !self.owns_row(binding, cache, layer, (input, local))? { return Err(Error::IdentityMismatch); } input.identity().validate(txn.token(), txn.position(), layer)?; Ok(local) } + fn owns_context(&self, binding: &ModelBinding, layer: LayerId, context: &Context<'_>) -> bool { + self.binding.matches(&binding.identity()) && layer == self.layer && std::ptr::eq(context, self.context) + } + fn owns_row( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + layer: LayerId, + (input, local): (&super::super::gr::ResidualReady, usize), + ) -> Result { + Ok(std::ptr::eq(input, self.index.source(local)?) + && Rc::ptr_eq(&self.provider, &cache.qsa(binding, layer.get())?.weights)) + } /// The step's position as a row of the batch. fn local_index(&self, txn: &QwenStepTxn<'_, '_>) -> Result { let first = self.index.source(0)?.identity().position().get(); 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 71b017c2..34e9f73c 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 @@ -139,48 +139,57 @@ impl<'ctx> ScratchBuffers<'ctx> { query: &[f32], attend: impl FnOnce(&DeviceBuffer<'ctx>, &mut DeviceBuffer<'ctx>) -> Result<()>, ) -> Result<()> { - let result = (|| { - self.validate()?; - if self.attended.is_some() || self.gated.is_some() { - return Err(Error::IdentityMismatch); - } - self.put_f32(0, query)?; - let (q, rest) = self.roles.split_at_mut(1); - attend(q[0].as_ref().ok_or(Error::CudaExecution)?, rest[0].as_mut().ok_or(Error::CudaExecution)?)?; - // Same full original attended finite readback BEFORE the gate. - self.attended = Some(download(self.roles[1].as_ref().ok_or(Error::CudaExecution)?, Q)?); - Ok(()) - })(); + let result = self.attend_checked(query, attend); if let Err(error) = result { self.note(error); } result } + fn attend_checked( + &mut self, + query: &[f32], + attend: impl FnOnce(&DeviceBuffer<'ctx>, &mut DeviceBuffer<'ctx>) -> Result<()>, + ) -> Result<()> { + self.validate()?; + if self.attended.is_some() || self.gated.is_some() { + return Err(Error::IdentityMismatch); + } + self.put_f32(0, query)?; + let (q, rest) = self.roles.split_at_mut(1); + attend(q[0].as_ref().ok_or(Error::CudaExecution)?, rest[0].as_mut().ok_or(Error::CudaExecution)?)?; + // Same full original attended finite readback BEFORE the gate. + self.attended = Some(download(self.roles[1].as_ref().ok_or(Error::CudaExecution)?, Q)?); + Ok(()) + } fn gate(&mut self, values: &[f32]) -> Result<()> { - let result = (|| { - self.validate()?; - validate_values(self.attended.as_deref().ok_or(Error::IdentityMismatch)?, Q)?; - if self.gated.is_some() { - return Err(Error::IdentityMismatch); - } - validate_values(values, Q)?; - self.put_f32(2, values)?; - let (inputs, outputs) = self.roles.split_at_mut(3); - self.context - .qsa_gate_f32( - inputs[1].as_ref().ok_or(Error::CudaExecution)?, - inputs[2].as_ref().ok_or(Error::CudaExecution)?, - outputs[0].as_mut().ok_or(Error::CudaExecution)?, - ) - .map_err(attention_driver_error)?; - self.gated = Some(download(outputs[0].as_ref().ok_or(Error::CudaExecution)?, Q)?); - Ok(()) - })(); + let result = self.gate_checked(values); if let Err(error) = result { self.note(error); } result } + fn gate_checked(&mut self, values: &[f32]) -> Result<()> { + self.check_gate_inputs(values)?; + self.put_f32(2, values)?; + let (inputs, outputs) = self.roles.split_at_mut(3); + self.context + .qsa_gate_f32( + inputs[1].as_ref().ok_or(Error::CudaExecution)?, + inputs[2].as_ref().ok_or(Error::CudaExecution)?, + outputs[0].as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(attention_driver_error)?; + self.gated = Some(download(outputs[0].as_ref().ok_or(Error::CudaExecution)?, Q)?); + Ok(()) + } + fn check_gate_inputs(&self, values: &[f32]) -> Result<()> { + self.validate()?; + validate_values(self.attended.as_deref().ok_or(Error::IdentityMismatch)?, Q)?; + if self.gated.is_some() { + return Err(Error::IdentityMismatch); + } + validate_values(values, Q) + } fn close(mut self) -> Result<()> { let primary = (self.failed.get() || self.context.is_poisoned()).then_some(Error::CudaExecution); self.reset(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs index 784a3382..3233f8bc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs @@ -48,11 +48,25 @@ impl NativeDecodeAttentionRow<'_, '_> { layer: LayerId, input: &ResidualReady, ) -> Result<(TokenLayer, Box<[f32]>, QsaPending)> { + let env = Env { binding, cache, txn }; + self.check_step(env, layer, input)?; + self.check_owners(env, layer, input)?; + self.pending.validate(&self.prior, self.identity)?; + validate_values(&self.values, 2560)?; + Ok((self.identity, self.values, self.pending)) + } + /// The input row, the step and the prior are the ones this row was attended at. + fn check_step(&self, env: Env<'_, '_, '_, '_>, layer: LayerId, input: &ResidualReady) -> Result<()> { + let Env { binding, txn, .. } = env; txn.validate_binding(&binding.identity())?; txn.validate_input(input.identity().token(), input.identity().position())?; self.identity.validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - txn.validate_qsa_prior(&self.prior, layer)?; + txn.validate_qsa_prior(&self.prior, layer) + } + /// The context, the source row, the weights and the transaction owner are the row's own. + fn check_owners(&self, env: Env<'_, '_, '_, '_>, layer: LayerId, input: &ResidualReady) -> Result<()> { + let Env { binding, cache, txn } = env; let context = cache.retained_context(binding, txn.cuda_context()?)?; let entry = cache.qsa(binding, layer.get())?; if !self.binding.matches(&binding.identity()) @@ -63,9 +77,7 @@ impl NativeDecodeAttentionRow<'_, '_> { { return Err(Error::IdentityMismatch); } - self.pending.validate(&self.prior, self.identity)?; - validate_values(&self.values, 2560)?; - Ok((self.identity, self.values, self.pending)) + Ok(()) } } @@ -191,8 +203,20 @@ fn append_attend( index: &QsaDecodeIndex<'_, '_, '_>, devices: &mut NativeDecodeDevices<'_, '_>, ) -> Result<(CompletedQsaKvAppend, Box<[f32]>)> { + let append = append_kv(env, prior, index, devices)?; + let attended = attend_selected(env, index, devices, &append)?; + Ok((append, attended)) +} + +/// The step's K/V appended to the owner-bound canonical INT8 prior. +fn append_kv( + env: Env<'_, '_, '_, '_>, + prior: &QsaPrior, + index: &QsaDecodeIndex<'_, '_, '_>, + devices: &mut NativeDecodeDevices<'_, '_>, +) -> Result { let Env { binding, cache, txn } = env; - let NativeDecodeDevices { attention, kv, stage, workspace, .. } = devices; + let NativeDecodeDevices { kv, stage, workspace, .. } = devices; // Owner-bound canonical INT8 prior; no arbitrary end or halfword conversion. let snapshot = prior.native_snapshot(kv)?; let append = index.with_completed_kv(binding, cache, txn, |k, v| { @@ -202,6 +226,18 @@ fn append_attend( if append.rows() != 1 { return Err(Error::IdentityMismatch); } + Ok(append) +} + +/// The appended K/V attended over the selected blocks; the attended values and the gate are finite. +fn attend_selected( + env: Env<'_, '_, '_, '_>, + index: &QsaDecodeIndex<'_, '_, '_>, + devices: &mut NativeDecodeDevices<'_, '_>, + append: &CompletedQsaKvAppend, +) -> Result> { + let Env { binding, cache, txn } = env; + let NativeDecodeDevices { attention, kv, workspace, .. } = devices; let attended = index.with_completed_buffers(binding, cache, txn, |q, ids, steps| { let inputs = QsaAttentionInputs::new(q, ids, steps, 1).map_err(driver)?; let actual = attention.attend(workspace, kv, append.final_snapshot(), &inputs).map_err(driver)?; @@ -212,7 +248,7 @@ fn append_attend( })?; validate_values(&attended, 6144)?; validate_values(index.gate(), 6144)?; - Ok((append, attended)) + Ok(attended) } /// Native decode gate F32 expf/multiply; Out is the original scalar Q8_1 diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs index b299a320..6a24150a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs @@ -42,27 +42,42 @@ impl QsaPrior { pub(in super::super) fn test_reset_replay_numeric_eq(&self, other: &Self) -> bool { self.layer() == other.layer() && self.next_position() == other.next_position() - && match (&self.0.native_kv, &other.0.native_kv) { - (Some(a), Some(b)) => a.logical_payload_eq(b), - (None, None) => true, - _ => false, - } - && self.0.pages.len() == other.0.pages.len() - && self.0.pooled.len() == other.0.pooled.len() + && self.same_native_kv(other) + && self.same_pages(other) + && self.same_pooled(other) + && self.0.tail.iter().zip(other.0.tail.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) + && self.0.dead.iter().zip(other.0.dead.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) + } + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn same_native_kv(&self, other: &Self) -> bool { + match (&self.0.native_kv, &other.0.native_kv) { + (Some(a), Some(b)) => a.logical_payload_eq(b), + (None, None) => true, + _ => false, + } + } + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn same_pages(&self, other: &Self) -> bool { + self.0.pages.len() == other.0.pages.len() && self .0 .pages .iter() .zip(other.0.pages.iter()) .all(|(a, b)| a.k.as_ref() == b.k.as_ref() && a.v.as_ref() == b.v.as_ref()) + } + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn same_pooled(&self, other: &Self) -> bool { + self.0.pooled.len() == other.0.pooled.len() && self .0 .pooled .iter() .zip(other.0.pooled.iter()) .all(|(a, b)| a.iter().zip(b.iter()).all(|(x, y)| x.to_bits() == y.to_bits())) - && self.0.tail.iter().zip(other.0.tail.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) - && self.0.dead.iter().zip(other.0.dead.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -173,23 +188,28 @@ impl QsaPrior { } validate_ids(ids, self.0.next_position)?; let bytes = ids.len().checked_mul(KV * 2).ok_or(Error::Overflow)?; - let mut k = reserve(bytes)?; - let mut v = reserve(bytes)?; + let mut k: Vec = reserve(bytes)?; + let mut v: Vec = reserve(bytes)?; for &id in ids { - let cell = usize::try_from(id).map_err(|_| Error::InvalidPosition)?; - let page = self.0.pages.get(cell / 4).ok_or(Error::InvalidPosition)?; - for h in 0..2 { - let start = (h * 4 + cell % 4) * 256; - for i in start..start + 256 { - let kh = page.k[i]; - let vh = page.v[i]; - validate_half(kh)?; - validate_half(vh)?; - k.extend_from_slice(&kh.to_le_bytes()); - v.extend_from_slice(&vh.to_le_bytes()); - } - } + self.gather_cell(id, (&mut k, &mut v))?; } Ok((k.into_boxed_slice(), v.into_boxed_slice())) } + /// The halfwords of the two heads of cell `id`, checked finite, appended to `k` and `v`. + fn gather_cell(&self, id: i32, (k, v): (&mut Vec, &mut Vec)) -> Result<()> { + let cell = usize::try_from(id).map_err(|_| Error::InvalidPosition)?; + let page = self.0.pages.get(cell / 4).ok_or(Error::InvalidPosition)?; + for h in 0..2 { + let start = (h * 4 + cell % 4) * 256; + for i in start..start + 256 { + let kh = page.k[i]; + let vh = page.v[i]; + validate_half(kh)?; + validate_half(vh)?; + k.extend_from_slice(&kh.to_le_bytes()); + v.extend_from_slice(&vh.to_le_bytes()); + } + } + Ok(()) + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs index 87bfcbd7..27ca65ed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs @@ -77,8 +77,7 @@ impl QsaIndexStage { let candidate = pending.next.clone(); let full = prep.project_column(QsaMatrixRole::Q, txn, cache, source, columns)?; let (q, gate) = prep.query_stage(&full)?; - let iq = prep.index_query(&prep.project(QsaMatrixRole::IndexQ, cache, source)?)?; - let ids = prep.select_ids(cache, &candidate, &iq)?; + let ids = prep.index_ids(cache, source, &candidate)?; drop(input_lease); Ok(prep.prepared(q, gate, ids, candidate, pending)) } @@ -205,7 +204,7 @@ impl QsaPrep<'_, '_, '_> { let k = norm(context, k, weights.k_norm(), Norm::K, norms.map(|v| v[1]))?; let k = rope(context, &k, p, Norm::K)?; let (kh, vh) = pack(context, &k, v)?; - let index = append(context, raw, weights.index_k_norm(), &self.prior.raw_prior()?, p, norms.map(|v| v[3]))?; + let index = append(context, (raw, weights.index_k_norm()), &self.prior.raw_prior()?, p, norms.map(|v| v[3]))?; QsaPending::new(self.prior, self.input.identity(), &kh, &vh, &index) } /// The query and the gate out of the full Q projection. @@ -214,6 +213,16 @@ impl QsaPrep<'_, '_, '_> { let q = norm(self.context, &q, self.weights.q_norm(), Norm::Q, self.norms.map(|v| v[0]))?; Ok((rope(self.context, &q, self.p, Norm::Q)?, gate)) } + /// The index query projected, normed and rotated, and the blocks it selects over the candidate. + fn index_ids( + &self, + cache: Option<&DenseWeightCache<'_>>, + source: Option<&QsaInputLease<'_, '_, '_>>, + candidate: &QsaPrior, + ) -> Result> { + let iq = self.index_query(&self.project(QsaMatrixRole::IndexQ, cache, source)?)?; + self.select_ids(cache, candidate, &iq) + } fn index_query(&self, iq: &[f32]) -> Result> { let iq = norm(self.context, iq, self.weights.index_q_norm(), Norm::Index, self.norms.map(|v| v[2]))?; rope(self.context, &iq, self.p, Norm::Index) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs index da67643e..8cecb516 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs @@ -8,15 +8,19 @@ impl QsaPending { let pos = Self::admit(prior, identity, k, v, index)?; let page = Rc::new(Self::next_page(prior, pos, k, v)?); let pages = if pos % 4 == 0 { prior.0.pages.appended(page)? } else { prior.0.pages.replace_last(page)? }; - let pooled = if pos % 4 == 3 { - prior.0.pooled.appended(Rc::new(index[512..640].try_into().map_err(|_| Error::InvalidDimension)?))? - } else { - prior.0.pooled.clone() - }; + let pooled = Self::next_pooled(prior, pos, index)?; let (tail, dead) = Self::next_tail(prior, pos, index)?; let next = Self::successor(prior, pages, pooled, tail, dead)?; Ok(Self { prior: prior.clone(), next, identity }) } + /// The pooled keys of the successor: one more when the step completes a block of four. + fn next_pooled(prior: &QsaPrior, pos: usize, index: &[f32]) -> Result> { + if pos % 4 == 3 { + prior.0.pooled.appended(Rc::new(index[512..640].try_into().map_err(|_| Error::InvalidDimension)?)) + } else { + Ok(prior.0.pooled.clone()) + } + } /// The prior is the state the step starts from; returns the step's position. fn admit(prior: &QsaPrior, identity: TokenLayer, k: &[u8], v: &[u8], index: &[f32]) -> Result { prior.validate_extent()?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs index 6f59d1cb..1934d28c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs @@ -11,21 +11,47 @@ pub(super) fn norm( resident: Option<&DeviceBuffer<'_>>, ) -> Result> { let a = upload(context, x)?; - let owned = if resident.is_none() { Some(upload(context, gamma)?) } else { None }; + let owned = upload_gamma(context, gamma, resident)?; let g = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut y = allocate(context, x.len())?; - match which { - Norm::Q => context.qsa_norm_q(&a, g, &mut y), - Norm::K => context.qsa_norm_k(&a, g, &mut y), - Norm::Index => context.qsa_norm_index_q(&a, g, &mut y), - } - .map_err(driver_error)?; + run_norm(context, which, (&a, g, &mut y))?; let out = download(&y, x.len())?; release([a, y])?; + release_gamma(owned)?; + Ok(out) +} +/// The gamma weights uploaded for this call, unless the caller has them resident. +fn upload_gamma<'c>( + context: &'c Context<'_>, + gamma: &[f32], + resident: Option<&DeviceBuffer<'_>>, +) -> Result>> { + Ok(if resident.is_none() { Some(upload(context, gamma)?) } else { None }) +} +fn release_gamma(owned: Option>) -> Result<()> { if let Some(v) = owned { v.release().map_err(driver_error)?; } - Ok(out) + Ok(()) +} +fn run_norm( + context: &Context<'_>, + which: Norm, + (a, g, y): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &mut DeviceBuffer<'_>), +) -> Result<()> { + match which { + Norm::Q => context.qsa_norm_q(a, g, y), + Norm::K => context.qsa_norm_k(a, g, y), + Norm::Index => context.qsa_norm_index_q(a, g, y), + } + .map_err(driver_error) +} +/// Every `(values, count)` is finite and of its count. +fn validate_each(inputs: &[(&[f32], usize)]) -> Result<()> { + for &(values, count) in inputs { + validate_values(values, count)?; + } + Ok(()) } pub(super) fn rope(context: &Context<'_>, x: &[f32], p: u32, which: Norm) -> Result> { let a = upload(context, x)?; @@ -51,8 +77,7 @@ pub(super) fn split(context: &Context<'_>, full: &[f32]) -> Result { Ok(out) } pub(super) fn pack(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result { - validate_values(k, KV)?; - validate_values(v, KV)?; + validate_each(&[(k, KV), (v, KV)])?; let k = upload(context, k)?; let v = upload(context, v)?; let mut kh = context.allocate(KV * 2).map_err(driver_error)?; @@ -64,28 +89,28 @@ pub(super) fn pack(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result, - raw: &[f32], - gamma: &[f32], + (raw, gamma): (&[f32], &[f32]), prior: &[f32], p: u32, resident: Option<&DeviceBuffer<'_>>, ) -> Result> { - validate_values(raw, 128)?; - validate_values(gamma, 128)?; - validate_values(prior, 512)?; + validate_each(&[(raw, 128), (gamma, 128), (prior, 512)])?; let x = upload(context, raw)?; - let owned = if resident.is_none() { Some(upload(context, gamma)?) } else { None }; + let owned = upload_gamma(context, gamma, resident)?; let g = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; - let old = upload(context, prior)?; - let mut next = allocate(context, 640)?; + let (old, mut next) = append_scratch(context, prior)?; context.qsa_index_append(&x, g, &old, &mut next, p).map_err(driver_error)?; let out = download(&next, 640)?; release([x, old, next])?; - if let Some(v) = owned { - v.release().map_err(driver_error)?; - } + release_gamma(owned)?; Ok(out) } +/// The prior index state uploaded, and the output of the next one allocated. +fn append_scratch<'c>(context: &'c Context<'_>, prior: &[f32]) -> Result<(DeviceBuffer<'c>, DeviceBuffer<'c>)> { + let old = upload(context, prior)?; + let next = allocate(context, 640)?; + Ok((old, next)) +} pub(super) fn select(context: &Context<'_>, pooled: &[f32], dead: &[f32], iq: &[f32], p: u32) -> Result> { let blocks = (p as usize + 1) / 4 + 1; validate_values(pooled, blocks * 128)?; @@ -108,8 +133,22 @@ pub(super) fn select_with_keys( retained: bool, ) -> Result> { let blocks = (p as usize + 1) / 4 + 1; - validate_values(dead, 128)?; - validate_values(iq, 512)?; + validate_each(&[(dead, 128), (iq, 512)])?; + let (dead, q, scores) = score_blocks(context, keys, (dead, iq), (blocks, p, retained))?; + let mut ids = context.allocate(2051 * 4).map_err(driver_error)?; + ids.copy_from(&[0xff; 2051 * 4]).map_err(driver_error)?; + context.qsa_block_topk(&scores, &mut ids, p).map_err(driver_error)?; + let out = read_ids(&ids, p)?; + release([dead, q, scores, ids])?; + Ok(out) +} +/// The dead keys and the query uploaded and the block scores computed (and read back once, checked finite). +fn score_blocks<'c>( + context: &'c Context<'_>, + keys: &DeviceBuffer<'_>, + (dead, iq): (&[f32], &[f32]), + (blocks, p, retained): (usize, u32, bool), +) -> Result<(DeviceBuffer<'c>, DeviceBuffer<'c>, DeviceBuffer<'c>)> { let dead = upload(context, dead)?; let q = upload(context, iq)?; let mut scores = allocate(context, blocks)?; @@ -120,12 +159,7 @@ pub(super) fn select_with_keys( } .map_err(driver_error)?; let _checked = download(&scores, blocks)?; - let mut ids = context.allocate(2051 * 4).map_err(driver_error)?; - ids.copy_from(&[0xff; 2051 * 4]).map_err(driver_error)?; - context.qsa_block_topk(&scores, &mut ids, p).map_err(driver_error)?; - let out = read_ids(&ids, p)?; - release([dead, q, scores, ids])?; - Ok(out) + Ok((dead, q, scores)) } /// The selected block ids the top-k kernel left in `ids`, validated for position `p`. fn read_ids(ids: &DeviceBuffer<'_>, p: u32) -> Result> { @@ -151,8 +185,7 @@ pub(in super::super) fn project( let a = upload(context, x)?; let mut owned = None; let (matrix, kind) = if let Some(cache) = cache { - let entry = cache.qsa(binding, w.layer())?; - cache.qsa_matrix(entry, role)? + cached_matrix(cache, binding, w, role)? } else { let (buffer, kind) = upload_matrix(context, binding, w, role, r)?; owned = Some(buffer); @@ -160,9 +193,28 @@ pub(in super::super) fn project( }; let mut y = allocate(context, r)?; dispatch_projection(context, matrix, &a, &mut y, kind, c, r).map_err(driver_error)?; - let values = download(&y, r)?; + finish_projection(y, owned, a, r) +} +/// The role's matrix the cache keeps resident for the layer of `w`. +fn cached_matrix<'a, 'ctx>( + cache: &'a DenseWeightCache<'ctx>, + binding: &ModelBinding, + w: &QsaWeights, + role: QsaMatrixRole, +) -> Result<(&'a DeviceBuffer<'ctx>, QsaMatrixKind)> { + let entry = cache.qsa(binding, w.layer())?; + cache.qsa_matrix(entry, role) +} +/// The projection read back and checked finite, after the device buffers are released. +fn finish_projection( + y: DeviceBuffer<'_>, + owned: Option>, + a: DeviceBuffer<'_>, + rows: usize, +) -> Result> { + let values = download(&y, rows)?; release_projection(y, owned, a)?; - validate_values(&values, r)?; + validate_values(&values, rows)?; Ok(values) } /// The role's matrix from the binding, uploaded for a projection without a cache. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs index 413cb01a..f70552be 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs @@ -74,13 +74,7 @@ impl QsaPending { (old, pos, end): (&QsaKvSnapshot, usize, usize), kv: &QsaPromptKv<'_>, ) -> Result<()> { - if end > context() - || identity.layer() != prior.layer() - || identity.position().get() != pos as u64 - || snapshot.next_position() != end - || index.end_position() as usize != end - || !old.owner_id().same_owner(&snapshot.owner_id()) - { + if Self::foreign_completion(prior, identity, (snapshot, index), (old, pos, end)) { return Err(Error::IdentityMismatch); } kv.validate_snapshot(snapshot).map_err(driver_error)?; @@ -92,6 +86,20 @@ impl QsaPending { } Ok(()) } + /// The completion is past the context, or not the prior's next cell of the same owner. + fn foreign_completion( + prior: &QsaPrior, + identity: TokenLayer, + (snapshot, index): (&QsaKvSnapshot, &QsaPromptIndexPrefix<'_>), + (old, pos, end): (&QsaKvSnapshot, usize, usize), + ) -> bool { + end > context() + || identity.layer() != prior.layer() + || identity.position().get() != pos as u64 + || snapshot.next_position() != end + || index.end_position() as usize != end + || !old.owner_id().same_owner(&snapshot.owner_id()) + } /// Preserve the persistent predecessor directory. A completed block adds /// one genuine key; future batch keys are never inserted in this prefix. fn completed_pooled( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs index 0f0d9930..c5cd91d1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs @@ -16,21 +16,6 @@ use std::rc::Rc; const ROLES: [QsaMatrixRole; 5] = [QsaMatrixRole::K, QsaMatrixRole::V, QsaMatrixRole::Q, QsaMatrixRole::IndexK, QsaMatrixRole::IndexQ]; const WIDTHS: [usize; 5] = [512, 512, 12288, 128, 512]; -fn native_error(error: leleka_cuda_driver::Error) -> Error { - match error { - leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, - other => super::qsa_index::driver_error(other), - } -} -fn native(kind: QsaMatrixKind) -> Result { - Ok(match kind { - QsaMatrixKind::Q4K => QsaNativeKind::Q4K, - QsaMatrixKind::Q5K => QsaNativeKind::Q5K, - QsaMatrixKind::Q6K => QsaNativeKind::Q6K, - QsaMatrixKind::Iq4Xs => QsaNativeKind::Iq4Xs, - QsaMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::QsaIndex)), - }) -} pub(super) struct NativeProjectionRow<'source, 'ctx> { binding: BindingIdentity, origin: TargetStepOrigin, @@ -40,339 +25,48 @@ pub(super) struct NativeProjectionRow<'source, 'ctx> { provider: Rc, values: [Option>; 5], } -impl<'source> NativeProjectionRow<'source, '_> { - pub(super) fn validate( - &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, - ) -> Result<()> { - txn.validate_projection_branch(&self.origin)?; - txn.validate_input(input.identity().token(), input.identity().position())?; - let context = txn.cuda_context()?; - cache.retained_context(binding, context)?; - let entry = cache.qsa(binding, layer.get())?; - if !self.binding.matches(&binding.identity()) - || !std::ptr::eq(self.context, context) - || self.layer != layer - || !std::ptr::eq(self.source, input) - || self.source.identity() != input.identity() - || !Rc::ptr_eq(&self.provider, &entry.weights) - { - return Err(Error::IdentityMismatch); - } - input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - for (values, n) in self.values.iter().zip(WIDTHS) { - if let Some(values) = values { - validate_values(values, n)?; - } - } - Ok(()) - } - pub(super) fn validate_fresh( - &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, - ) -> Result<()> { - self.validate(binding, cache, txn, layer, input)?; - if self.values.iter().any(Option::is_none) { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - pub(super) fn source(&self) -> &'source ResidualReady { - self.source - } - pub(super) fn attend_origin( - &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - identity: super::contract::TokenLayer, - ) -> Result { - self.validate(binding, cache, txn, layer, self.source)?; - if identity != self.source.identity() { - return Err(Error::IdentityMismatch); - } - Ok(self.origin.clone()) - } - pub(super) fn take_prompt( - &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, - chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, - local: usize, - role: QsaMatrixRole, - ) -> Result> { - self.origin.validate(chunk.original_session()?)?; - let context = cache.retained_context(binding, chunk.context()?)?; - let entry = cache.qsa(binding, layer.get())?; - let index = chunk.micro_row_index(local)?; - chunk.validate_attention_input(index, layer, self.source)?; - let (token, pos) = chunk.row_ids(index)?; - self.source.identity().validate(token, pos, layer)?; - self.source.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - if !self.binding.matches(&binding.identity()) - || self.layer != layer - || !std::ptr::eq(context, self.context) - || !Rc::ptr_eq(&entry.weights, &self.provider) - { - return Err(Error::IdentityMismatch); - } - let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; - let values = self.values[i].as_ref().ok_or(Error::IdentityMismatch)?; - validate_values(values, WIDTHS[i])?; - self.values[i].take().ok_or(Error::IdentityMismatch) - } - pub(super) fn take( - &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, - role: QsaMatrixRole, - ) -> Result> { - self.validate(binding, cache, txn, layer, input)?; - let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; - self.values[i].take().ok_or(Error::IdentityMismatch) - } -} -#[allow(clippy::too_many_arguments)] // Genuine chunk and separately admitted fixed native owners. -pub(super) fn project<'source, 'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, - inputs: &[&'source ResidualReady], - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result>> { - let context = cache.retained_context(binding, chunk.context()?)?; - let origin = chunk.original_session()?.target_origin()?; - let t = inputs.len(); - if t == 0 || t > owner.capacity() || t != chunk.micro_len()? { - return Err(Error::InvalidDimension); - } - check_inputs(binding, chunk, layer, inputs)?; - let entry = cache.qsa(binding, layer.get())?; - let batches = project_batches(cache, entry, inputs, owner, workspace)?; - split_rows((binding, context, &origin, layer), inputs, &entry.weights, &batches) -} -/// Every input is the chunk's own attention row, finite, distinct and in consecutive positions. -fn check_inputs( - binding: &ModelBinding, - chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, - inputs: &[&ResidualReady], -) -> Result<()> { - for (local, input) in inputs.iter().enumerate() { - let index = chunk.micro_row_index(local)?; - chunk.validate_attention_input(index, layer, input)?; - let (token, pos) = chunk.row_ids(index)?; - input.identity().validate(token, pos, layer)?; - input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - validate_values(input.mixed(), 2560)?; - if inputs[..local].iter().any(|prior| std::ptr::eq(*prior, *input)) { - return Err(Error::IdentityMismatch); - } - if local > 0 && inputs[local - 1].identity().position().get().checked_add(1) != Some(pos.get()) { - return Err(Error::InvalidPosition); - } - } - Ok(()) -} -/// The five whole-batch projections of the rows, each checked finite. -fn project_batches<'ctx>( - cache: &DenseWeightCache<'ctx>, - entry: &QsaResident, - inputs: &[&ResidualReady], - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result<[Box<[f32]>; 5]> { - let t = inputs.len(); - check_shapes(entry)?; - let (weights, kinds) = retained_matrices(cache, entry)?; - let mut mixed = Vec::new(); - mixed.try_reserve_exact(t * 2560).map_err(|_| Error::InputAllocation)?; - for input in inputs { - mixed.extend_from_slice(input.mixed()); - } - let kinds = [native(kinds[0])?, native(kinds[1])?, native(kinds[2])?]; - let output = owner.project_inputs(t, &mixed, weights, kinds, workspace).map_err(native_error)?; - let batches = [output.k, output.v, output.q, output.index_k, output.index_q]; - for (values, n) in batches.iter().zip(WIDTHS) { - validate_values(values, t * n)?; - } - Ok(batches) -} -fn check_shapes(entry: &QsaResident) -> Result<()> { - for (role, n) in ROLES.into_iter().zip(WIDTHS) { - if entry.weights.shape(role) != (2560, n) { - return Err(Error::InvalidDimension); - } - } - Ok(()) -} -/// All Original need() weights are genuine retained whole matrices: (K V Q IndexK IndexQ, kinds of K V Q). -fn retained_matrices<'c, 'ctx>( - cache: &'c DenseWeightCache<'ctx>, - entry: &QsaResident, -) -> Result<([&'c DeviceBuffer<'ctx>; 5], [QsaMatrixKind; 3])> { - let (k, kk) = cache.qsa_matrix(entry, QsaMatrixRole::K)?; - let (v, vk) = cache.qsa_matrix(entry, QsaMatrixRole::V)?; - let (q, qk) = cache.qsa_matrix(entry, QsaMatrixRole::Q)?; - let (ik, ikk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexK)?; - let (iq, iqk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexQ)?; - if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { - return Err(Error::Unsupported(Stage::QsaIndex)); - } - Ok(([k, v, q, ik, iq], [kk, vk, qk])) -} -/// The per-row capabilities, each carrying its own copy of the row of every batch. -fn split_rows<'source, 'ctx>( - (binding, context, origin, layer): (&ModelBinding, &'ctx Context<'ctx>, &TargetStepOrigin, LayerId), - inputs: &[&'source ResidualReady], - provider: &Rc, - batches: &[Box<[f32]>; 5], -) -> Result>> { - // Full whole-batch finite checks precede every row capability allocation. - let mut result = Vec::new(); - result.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; - for (local, source) in inputs.iter().enumerate() { - let values = row_values(batches, local)?; - let provider = provider.clone(); - result.push(NativeProjectionRow { - binding: binding.identity(), - origin: origin.clone(), - context, - layer, - source, - provider, - values, - }); - } - Ok(result) -} -fn row_values(batches: &[Box<[f32]>; 5], local: usize) -> Result<[Option>; 5]> { - let mut values: [Option>; 5] = std::array::from_fn(|_| None); - for i in 0..5 { - let n = WIDTHS[i]; - let mut row = Vec::new(); - row.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; - row.extend_from_slice(&batches[i][local * n..(local + 1) * n]); - values[i] = Some(row.into_boxed_slice()); - } - Ok(values) -} pub(super) struct NativeOutRow<'ctx> { binding: BindingIdentity, identity: super::contract::TokenLayer, context: &'ctx Context<'ctx>, values: Box<[f32]>, } -impl NativeOutRow<'_> { - pub(super) fn take( - self, - binding: &BindingIdentity, - identity: super::contract::TokenLayer, - context: &Context<'_>, - ) -> Result> { - if !self.binding.matches(binding) || self.identity != identity || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - validate_values(&self.values, 2560)?; - Ok(self.values) - } -} -#[allow(clippy::too_many_arguments)] // Actual attention producers and current chunk fence. -pub(super) fn project_out<'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, - rows: &[super::qsa_attention::NativeAttended<'_, 'ctx>], - proofs: &[super::session::chunk::PreparedLayerRow], - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result> { - let context = cache.retained_context(binding, chunk.context()?)?; - let t = rows.len(); - if t == 0 || t > owner.capacity() || t != chunk.micro_len()? || proofs.len() != t { - return Err(Error::InvalidDimension); - } - let entry = cache.qsa(binding, layer.get())?; - let (attended, gates) = gather_rows(binding, cache, (chunk, layer), (rows, proofs), context)?; - let output = project_rows(cache, entry, (&attended, &gates), owner, workspace)?; - ready_rows(binding, cache, (chunk, layer), (rows, proofs), (context, &output)) -} -/// The Out projection of all gathered rows, checked finite. -fn project_rows<'ctx>( - cache: &DenseWeightCache<'ctx>, - entry: &QsaResident, - (attended, gates): (&[f32], &[f32]), - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result> { - let t = attended.len() / 6144; - if entry.weights.shape(QsaMatrixRole::Out) != (6144, 2560) { - return Err(Error::InvalidDimension); - } - let (weight, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; - let output = owner.project_out(t, attended, gates, weight, native(kind)?, workspace).map_err(native_error)?; - validate_values(&output, t * 2560)?; - Ok(output) -} -/// The attended values and gates of every validated row, back to back. -fn gather_rows<'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - (chunk, layer): (&QwenChunkTxn<'_, '_>, LayerId), - (rows, proofs): (&[super::qsa_attention::NativeAttended<'_, 'ctx>], &[super::session::chunk::PreparedLayerRow]), - context: &Context<'_>, -) -> Result<(Vec, Vec)> { - let t = rows.len(); - let mut attended = Vec::new(); - let mut gates = Vec::new(); - attended.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; - gates.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; - for (local, row) in rows.iter().enumerate() { - row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; - attended.extend_from_slice(row.values()); - gates.extend_from_slice(row.gate()); - } - Ok((attended, gates)) -} -/// Each row re-validated, then given back its own slice of the Out projection. -fn ready_rows<'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - (chunk, layer): (&QwenChunkTxn<'_, '_>, LayerId), - (rows, proofs): (&[super::qsa_attention::NativeAttended<'_, 'ctx>], &[super::session::chunk::PreparedLayerRow]), - (context, output): (&'ctx Context<'ctx>, &[f32]), -) -> Result> { - let t = rows.len(); - let mut ready = Vec::new(); - ready.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; - for (local, row) in rows.iter().enumerate() { - row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; - let mut values = Vec::new(); - values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; - values.extend_from_slice(&output[local * 2560..(local + 1) * 2560]); - let values = values.into_boxed_slice(); - ready.push( - row.ready( - binding, - NativeOutRow { binding: binding.identity(), identity: row.identity(), context, values }, - )?, - ); - } - Ok(ready) -} + +mod native_error_fn; +#[allow(unused_imports)] +use native_error_fn::check_batch; +#[allow(unused_imports)] +use native_error_fn::check_input; +#[allow(unused_imports)] +use native_error_fn::check_inputs; +#[allow(unused_imports)] +use native_error_fn::chunk_owners; +#[allow(unused_imports)] +use native_error_fn::native; +#[allow(unused_imports)] +use native_error_fn::native_error; +#[allow(unused_imports)] +pub(super) use native_error_fn::project; +#[allow(unused_imports)] +use native_error_fn::project_batches; +mod concat_mixed_fn; +#[allow(unused_imports)] +use concat_mixed_fn::check_batches; +#[allow(unused_imports)] +use concat_mixed_fn::check_shapes; +#[allow(unused_imports)] +use concat_mixed_fn::concat_mixed; +#[allow(unused_imports)] +use concat_mixed_fn::gather_rows; +#[allow(unused_imports)] +pub(super) use concat_mixed_fn::project_out; +#[allow(unused_imports)] +use concat_mixed_fn::project_rows; +#[allow(unused_imports)] +use concat_mixed_fn::ready_rows; +#[allow(unused_imports)] +use concat_mixed_fn::retained_matrices; +#[allow(unused_imports)] +use concat_mixed_fn::row_values; +#[allow(unused_imports)] +use concat_mixed_fn::split_rows; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs new file mode 100644 index 00000000..3744068a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs @@ -0,0 +1,184 @@ +//! Moved out of the parent module by STRA-338: fn concat_mixed, fn check_batches, fn check_shapes, fn retained_matrices, fn split_rows, fn row_values .... + +#[allow(unused_imports)] +use super::*; + +/// The mixed rows of all inputs, one after the other. +pub(super) fn concat_mixed(inputs: &[&ResidualReady]) -> Result> { + let mut mixed = Vec::new(); + mixed.try_reserve_exact(inputs.len() * 2560).map_err(|_| Error::InputAllocation)?; + for input in inputs { + mixed.extend_from_slice(input.mixed()); + } + Ok(mixed) +} +/// Each of the five batches is finite and `t` rows of its width. +pub(super) fn check_batches(batches: &[Box<[f32]>; 5], t: usize) -> Result<()> { + for (values, n) in batches.iter().zip(WIDTHS) { + validate_values(values, t * n)?; + } + Ok(()) +} +pub(super) fn check_shapes(entry: &QsaResident) -> Result<()> { + for (role, n) in ROLES.into_iter().zip(WIDTHS) { + if entry.weights.shape(role) != (2560, n) { + return Err(Error::InvalidDimension); + } + } + Ok(()) +} +/// All Original need() weights are genuine retained whole matrices: (K V Q IndexK IndexQ, kinds of K V Q). +pub(super) fn retained_matrices<'c, 'ctx>( + cache: &'c DenseWeightCache<'ctx>, + entry: &QsaResident, +) -> Result<([&'c DeviceBuffer<'ctx>; 5], [QsaMatrixKind; 3])> { + let (k, kk) = cache.qsa_matrix(entry, QsaMatrixRole::K)?; + let (v, vk) = cache.qsa_matrix(entry, QsaMatrixRole::V)?; + let (q, qk) = cache.qsa_matrix(entry, QsaMatrixRole::Q)?; + let (ik, ikk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexK)?; + let (iq, iqk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexQ)?; + if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::QsaIndex)); + } + Ok(([k, v, q, ik, iq], [kk, vk, qk])) +} +/// The per-row capabilities, each carrying its own copy of the row of every batch. +pub(super) fn split_rows<'source, 'ctx>( + (binding, context, origin, layer): (&ModelBinding, &'ctx Context<'ctx>, &TargetStepOrigin, LayerId), + inputs: &[&'source ResidualReady], + provider: &Rc, + batches: &[Box<[f32]>; 5], +) -> Result>> { + // Full whole-batch finite checks precede every row capability allocation. + let mut result = Vec::new(); + result.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; + for (local, source) in inputs.iter().enumerate() { + let values = row_values(batches, local)?; + let provider = provider.clone(); + result.push(NativeProjectionRow { + binding: binding.identity(), + origin: origin.clone(), + context, + layer, + source, + provider, + values, + }); + } + Ok(result) +} +pub(super) fn row_values(batches: &[Box<[f32]>; 5], local: usize) -> Result<[Option>; 5]> { + let mut values: [Option>; 5] = std::array::from_fn(|_| None); + for i in 0..5 { + let n = WIDTHS[i]; + let mut row = Vec::new(); + row.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + row.extend_from_slice(&batches[i][local * n..(local + 1) * n]); + values[i] = Some(row.into_boxed_slice()); + } + Ok(values) +} +impl NativeOutRow<'_> { + pub(in super::super) fn take( + self, + binding: &BindingIdentity, + identity: super::super::contract::TokenLayer, + context: &Context<'_>, + ) -> Result> { + if !self.binding.matches(binding) || self.identity != identity || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + validate_values(&self.values, 2560)?; + Ok(self.values) + } +} +#[allow(clippy::too_many_arguments)] // Actual attention producers and current chunk fence. +pub(in super::super) fn project_out<'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + rows: &[super::super::qsa_attention::NativeAttended<'_, 'ctx>], + proofs: &[super::super::session::chunk::PreparedLayerRow], + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let context = cache.retained_context(binding, chunk.context()?)?; + check_batch(rows.len(), owner.capacity(), chunk)?; + if proofs.len() != rows.len() { + return Err(Error::InvalidDimension); + } + let entry = cache.qsa(binding, layer.get())?; + let (attended, gates) = gather_rows(binding, cache, (chunk, layer), (rows, proofs), context)?; + let output = project_rows(cache, entry, (&attended, &gates), owner, workspace)?; + ready_rows(binding, cache, (chunk, layer), (rows, proofs), (context, &output)) +} +/// The Out projection of all gathered rows, checked finite. +pub(super) fn project_rows<'ctx>( + cache: &DenseWeightCache<'ctx>, + entry: &QsaResident, + (attended, gates): (&[f32], &[f32]), + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let t = attended.len() / 6144; + if entry.weights.shape(QsaMatrixRole::Out) != (6144, 2560) { + return Err(Error::InvalidDimension); + } + let (weight, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; + let output = owner.project_out(t, attended, gates, weight, native(kind)?, workspace).map_err(native_error)?; + validate_values(&output, t * 2560)?; + Ok(output) +} +/// The attended values and gates of every validated row, back to back. +pub(super) fn gather_rows<'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + (chunk, layer): (&QwenChunkTxn<'_, '_>, LayerId), + (rows, proofs): ( + &[super::super::qsa_attention::NativeAttended<'_, 'ctx>], + &[super::super::session::chunk::PreparedLayerRow], + ), + context: &Context<'_>, +) -> Result<(Vec, Vec)> { + let t = rows.len(); + let mut attended = Vec::new(); + let mut gates = Vec::new(); + attended.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; + gates.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; + for (local, row) in rows.iter().enumerate() { + row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; + attended.extend_from_slice(row.values()); + gates.extend_from_slice(row.gate()); + } + Ok((attended, gates)) +} +/// Each row re-validated, then given back its own slice of the Out projection. +pub(super) fn ready_rows<'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + (chunk, layer): (&QwenChunkTxn<'_, '_>, LayerId), + (rows, proofs): ( + &[super::super::qsa_attention::NativeAttended<'_, 'ctx>], + &[super::super::session::chunk::PreparedLayerRow], + ), + (context, output): (&'ctx Context<'ctx>, &[f32]), +) -> Result> { + let t = rows.len(); + let mut ready = Vec::new(); + ready.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + for (local, row) in rows.iter().enumerate() { + row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; + let mut values = Vec::new(); + values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; + values.extend_from_slice(&output[local * 2560..(local + 1) * 2560]); + let values = values.into_boxed_slice(); + ready.push( + row.ready( + binding, + NativeOutRow { binding: binding.identity(), identity: row.identity(), context, values }, + )?, + ); + } + Ok(ready) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs new file mode 100644 index 00000000..b0ba8dd9 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs @@ -0,0 +1,242 @@ +//! Moved out of the parent module by STRA-338: fn native_error, fn native, impl NativeProjectionRow, fn project, fn chunk_owners, fn check_batch .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn native_error(error: leleka_cuda_driver::Error) -> Error { + match error { + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + other => super::super::qsa_index::driver_error(other), + } +} +pub(super) fn native(kind: QsaMatrixKind) -> Result { + Ok(match kind { + QsaMatrixKind::Q4K => QsaNativeKind::Q4K, + QsaMatrixKind::Q5K => QsaNativeKind::Q5K, + QsaMatrixKind::Q6K => QsaNativeKind::Q6K, + QsaMatrixKind::Iq4Xs => QsaNativeKind::Iq4Xs, + QsaMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::QsaIndex)), + }) +} +impl<'source> NativeProjectionRow<'source, '_> { + pub(in super::super) fn validate( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + ) -> Result<()> { + txn.validate_projection_branch(&self.origin)?; + txn.validate_input(input.identity().token(), input.identity().position())?; + let context = txn.cuda_context()?; + cache.retained_context(binding, context)?; + let entry = cache.qsa(binding, layer.get())?; + if !self.same_row(binding, context, (layer, input), &entry.weights) { + return Err(Error::IdentityMismatch); + } + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + self.check_values() + } + pub(super) fn same_row( + &self, + binding: &ModelBinding, + context: &Context<'_>, + (layer, input): (LayerId, &ResidualReady), + provider: &Rc, + ) -> bool { + self.binding.matches(&binding.identity()) + && std::ptr::eq(self.context, context) + && self.layer == layer + && std::ptr::eq(self.source, input) + && self.source.identity() == input.identity() + && Rc::ptr_eq(&self.provider, provider) + } + /// The projections still held are finite and of their widths. + pub(super) fn check_values(&self) -> Result<()> { + for (values, n) in self.values.iter().zip(WIDTHS) { + if let Some(values) = values { + validate_values(values, n)?; + } + } + Ok(()) + } + pub(in super::super) fn validate_fresh( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + ) -> Result<()> { + self.validate(binding, cache, txn, layer, input)?; + if self.values.iter().any(Option::is_none) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in super::super) fn source(&self) -> &'source ResidualReady { + self.source + } + pub(in super::super) fn attend_origin( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + identity: super::super::contract::TokenLayer, + ) -> Result { + self.validate(binding, cache, txn, layer, self.source)?; + if identity != self.source.identity() { + return Err(Error::IdentityMismatch); + } + Ok(self.origin.clone()) + } + pub(in super::super) fn take_prompt( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + local: usize, + role: QsaMatrixRole, + ) -> Result> { + self.origin.validate(chunk.original_session()?)?; + let context = cache.retained_context(binding, chunk.context()?)?; + let entry = cache.qsa(binding, layer.get())?; + self.check_prompt_source(binding, chunk, (layer, local))?; + if !self.owns_prompt(binding, context, (layer, &entry.weights)) { + return Err(Error::IdentityMismatch); + } + self.take_checked(role) + } + pub(super) fn owns_prompt( + &self, + binding: &ModelBinding, + context: &Context<'_>, + (layer, provider): (LayerId, &Rc), + ) -> bool { + self.binding.matches(&binding.identity()) + && self.layer == layer + && std::ptr::eq(context, self.context) + && Rc::ptr_eq(provider, &self.provider) + } + /// The source is the chunk's own attention row `local` of the layer, in its origin. + pub(super) fn check_prompt_source( + &self, + binding: &ModelBinding, + chunk: &QwenChunkTxn<'_, '_>, + (layer, local): (LayerId, usize), + ) -> Result<()> { + let index = chunk.micro_row_index(local)?; + chunk.validate_attention_input(index, layer, self.source)?; + let (token, pos) = chunk.row_ids(index)?; + self.source.identity().validate(token, pos, layer)?; + self.source.validate_origin(&binding.identity(), GrRole::Attention(layer.get())) + } + /// The role's projection, checked finite, handed out once. + pub(super) fn take_checked(&mut self, role: QsaMatrixRole) -> Result> { + let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; + let values = self.values[i].as_ref().ok_or(Error::IdentityMismatch)?; + validate_values(values, WIDTHS[i])?; + self.values[i].take().ok_or(Error::IdentityMismatch) + } + pub(in super::super) fn take( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + role: QsaMatrixRole, + ) -> Result> { + self.validate(binding, cache, txn, layer, input)?; + let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; + self.values[i].take().ok_or(Error::IdentityMismatch) + } +} +#[allow(clippy::too_many_arguments)] // Genuine chunk and separately admitted fixed native owners. +pub(in super::super) fn project<'source, 'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + inputs: &[&'source ResidualReady], + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result>> { + let (context, origin) = chunk_owners(binding, cache, chunk)?; + check_batch(inputs.len(), owner.capacity(), chunk)?; + check_inputs(binding, chunk, layer, inputs)?; + let entry = cache.qsa(binding, layer.get())?; + let batches = project_batches(cache, entry, inputs, owner, workspace)?; + split_rows((binding, context, &origin, layer), inputs, &entry.weights, &batches) +} +/// The context the cache retains for the chunk, and the origin of the chunk's target step. +pub(super) fn chunk_owners<'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, +) -> Result<(&'ctx Context<'ctx>, TargetStepOrigin)> { + let context = cache.retained_context(binding, chunk.context()?)?; + let origin = chunk.original_session()?.target_origin()?; + Ok((context, origin)) +} +/// The batch has rows, fits the owner and is exactly the chunk's micro batch. +pub(super) fn check_batch(t: usize, capacity: usize, chunk: &QwenChunkTxn<'_, '_>) -> Result<()> { + if t == 0 || t > capacity || t != chunk.micro_len()? { + return Err(Error::InvalidDimension); + } + Ok(()) +} +/// Every input is the chunk's own attention row, finite, distinct and in consecutive positions. +pub(super) fn check_inputs( + binding: &ModelBinding, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + inputs: &[&ResidualReady], +) -> Result<()> { + for local in 0..inputs.len() { + check_input(binding, chunk, layer, (inputs, local))?; + } + Ok(()) +} +pub(super) fn check_input( + binding: &ModelBinding, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + (inputs, local): (&[&ResidualReady], usize), +) -> Result<()> { + let input = inputs[local]; + let index = chunk.micro_row_index(local)?; + chunk.validate_attention_input(index, layer, input)?; + let (token, pos) = chunk.row_ids(index)?; + input.identity().validate(token, pos, layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + validate_values(input.mixed(), 2560)?; + if inputs[..local].iter().any(|prior| std::ptr::eq(*prior, input)) { + return Err(Error::IdentityMismatch); + } + if local > 0 && inputs[local - 1].identity().position().get().checked_add(1) != Some(pos.get()) { + return Err(Error::InvalidPosition); + } + Ok(()) +} +/// The five whole-batch projections of the rows, each checked finite. +pub(super) fn project_batches<'ctx>( + cache: &DenseWeightCache<'ctx>, + entry: &QsaResident, + inputs: &[&ResidualReady], + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result<[Box<[f32]>; 5]> { + let t = inputs.len(); + check_shapes(entry)?; + let (weights, kinds) = retained_matrices(cache, entry)?; + let mixed = concat_mixed(inputs)?; + let kinds = [native(kinds[0])?, native(kinds[1])?, native(kinds[2])?]; + let output = owner.project_inputs(t, &mixed, weights, kinds, workspace).map_err(native_error)?; + let batches = [output.k, output.v, output.q, output.index_k, output.index_q]; + check_batches(&batches, t)?; + Ok(batches) +}