From e148ef9bb21067f0e09c19fde2dc205f57b898ab Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:16:13 +0100 Subject: [PATCH] STRA-338 size2 en7: qsa prompt/resident/selected-cache and router scratch functions cut to the limits --- .../src/qwen_forward/qsa_prompt_device.rs | 185 +++++--- .../src/qwen_forward/qsa_prompt_index.rs | 284 ++++++----- .../impl_residentqsacompleted.rs | 12 +- .../impl_residentqsalayer.rs | 180 +++---- .../impl_residentqsalayer_2.rs | 70 ++- .../src/qwen_forward/qsa_resident_scalar.rs | 446 +++++++++++------- .../src/qwen_forward/qsa_selected_cache.rs | 181 ++++--- .../src/qwen_forward/router_scratch.rs | 118 ++--- .../src/qwen_forward/router_scratch_gpu.rs | 95 ++-- .../router_scratch_gpu/valid_reset_fn.rs | 263 +++++++---- 10 files changed, 1103 insertions(+), 731 deletions(-) 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 01bcb0bf..a4d27ee8 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 @@ -1,6 +1,7 @@ //! Genuine current prompt QSA over one affine physical arena. Canonical INT8 //! 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::session::{TargetStepOrigin, chunk::QwenChunkTxn}; use super::*; use leleka_cuda_driver::{ @@ -52,26 +53,12 @@ pub(in crate::qwen_forward) struct PromptDeviceQsaState<'ctx> { index: QsaPromptIndexState, kv: CompletedQsaKvAppend, } -#[allow(clippy::too_many_arguments)] -pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, +fn prompt_identities( chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, prior: &QsaPrior, - producer: &'lease mut OriginalQsaPromptDevice<'ctx>, - read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result> { - let context = cache.retained_context(binding, chunk.context()?)?; - cache.validate(binding)?; - chunk.validate_prompt_qsa_prior(layer, prior)?; - let t = read.rows(); - if t == 0 || t != chunk.micro_len()? || !read.context_matches(context) { - return Err(Error::IdentityMismatch); - } - let entry = cache.qsa(binding, layer.get())?; - let origin = chunk.original_session()?.target_origin()?; + layer: LayerId, + t: usize, +) -> Result> { let mut identities = Vec::new(); identities.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; let first = prior.next_position(); @@ -83,6 +70,9 @@ pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx } identities.push(TokenLayer::new(token, pos, layer)); } + Ok(identities) +} +fn check_prompt_shapes(entry: &QsaResident) -> Result<()> { for (role, n, k) in [ (QsaMatrixRole::K, 512, 2560), (QsaMatrixRole::V, 512, 2560), @@ -95,6 +85,14 @@ pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx return Err(Error::InvalidDimension); } } + Ok(()) +} +/// The six projection buffers (K, V, Q, IndexK, IndexQ, Out) and the kinds of K, V, Q, Out. +type PromptProjections<'a, 'ctx> = ([&'a DeviceBuffer<'ctx>; 6], [QsaMatrixKind; 4]); +fn prompt_projections<'a, 'ctx>( + cache: &'a DenseWeightCache<'ctx>, + entry: &QsaResident, +) -> Result> { let (k, kk) = cache.qsa_matrix(entry, ROLES[0])?; let (v, vk) = cache.qsa_matrix(entry, ROLES[1])?; let (q, qk) = cache.qsa_matrix(entry, ROLES[2])?; @@ -104,23 +102,60 @@ pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { return Err(Error::Unsupported(Stage::QsaIndex)); } + Ok(([k, v, q, ik, iq, out], [kk, vk, qk, ok])) +} +/// The guards of `prepare_prompt_device` before any device work: the weights lineage, the step origin and one +/// identity per micro row. +fn prompt_guards<'c, 'ctx>( + binding: &ModelBinding, + cache: &'c DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + (layer, prior): (LayerId, &QsaPrior), + read: &OriginalDeviceGrRead<'_, '_, 'ctx>, +) -> Result<(&'ctx Context<'ctx>, &'c QsaResident, TargetStepOrigin, Vec)> { + let context = cache.retained_context(binding, chunk.context()?)?; + cache.validate(binding)?; + chunk.validate_prompt_qsa_prior(layer, prior)?; + let t = read.rows(); + if t == 0 || t != chunk.micro_len()? || !read.context_matches(context) { + return Err(Error::IdentityMismatch); + } + let entry = cache.qsa(binding, layer.get())?; + let origin = chunk.original_session()?.target_origin()?; + Ok((context, entry, origin, prompt_identities(chunk, prior, layer, t)?)) +} +/// The device selection over the prior's native index image with the layer's projection weights. +fn prompt_select<'lease, 'arena, 'loan, 'ctx>( + cache: &DenseWeightCache<'ctx>, + entry: &QsaResident, + prior: &QsaPrior, + producer: &'lease mut OriginalQsaPromptDevice<'ctx>, + (read, workspace): (OriginalDeviceGrRead<'arena, 'loan, 'ctx>, &mut NativeBatchWorkspace<'ctx>), +) -> Result> { + let first = prior.next_position(); + check_prompt_shapes(entry)?; + let (projections, [kk, vk, qk, ok]) = prompt_projections(cache, entry)?; let (pooled, tail, dead) = prior.native_index_image()?; let norms = cache.qsa_norms(entry)?; - let selected = producer - .prepare( - read, - workspace, - u32::try_from(first).map_err(|_| Error::InvalidPosition)?, - &pooled, - &tail, - &dead, - OriginalQsaPromptWeights { - projections: [k, v, q, ik, iq, out], - kinds: [native(kk)?, native(vk)?, native(qk)?, native(ok)?], - norms, - }, - ) - .map_err(device_error)?; + let start = u32::try_from(first).map_err(|_| Error::InvalidPosition)?; + let kinds = [native(kk)?, native(vk)?, native(qk)?, native(ok)?]; + producer + .prepare(read, workspace, start, &pooled, &tail, &dead, OriginalQsaPromptWeights { projections, kinds, norms }) + .map_err(device_error) +} +#[allow(clippy::too_many_arguments)] +pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + prior: &QsaPrior, + producer: &'lease mut OriginalQsaPromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let (context, entry, origin, identities) = prompt_guards(binding, cache, chunk, (layer, prior), &read)?; + let selected = prompt_select(cache, entry, prior, producer, (read, workspace))?; chunk.validate_prompt_qsa_prior(layer, prior)?; cache.validate(binding)?; origin.validate(chunk.original_session()?)?; @@ -136,17 +171,12 @@ pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx }) } impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan, 'ctx> { - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn complete( - self, + fn check_inputs<'c>( + &self, binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + cache: &'c DenseWeightCache<'ctx>, chunk: &QwenChunkTxn<'_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - kv: &mut QsaPromptKv<'ctx>, - stage: &mut QsaPromptStage<'ctx>, - attention: &mut QsaPromptAttention<'ctx>, - ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, PromptDeviceQsaState<'ctx>)> { + ) -> Result<(&'ctx Context<'ctx>, &'c DeviceBuffer<'ctx>, QsaMatrixKind)> { self.origin.validate(chunk.original_session()?)?; chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; cache.validate(binding)?; @@ -159,41 +189,54 @@ impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan { return Err(Error::IdentityMismatch); } - for (local, id) in self.identities.iter().enumerate() { - let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; - id.validate(token, pos, self.layer)?; - } + check_rows(&self.identities, self.layer, chunk)?; let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; - let snapshot = self.prior.native_snapshot(kv)?; - let (block, index, appended) = self - .selected - .complete(workspace, kv, stage, snapshot, attention, out, native(kind)?) - .map_err(device_error)?; + 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>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, PromptDeviceQsaState<'ctx>)> { + 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)?; + let (block, index, appended) = + selected.complete(workspace, kv, stage, snapshot, attention, out, native(kind)?).map_err(device_error)?; + let state = + PromptDeviceQsaState { binding, origin, context, layer, prior, provider, identities, index, kv: appended }; + state.recheck(model, cache, chunk, ctx)?; + Ok((block, state)) + } +} +fn check_rows(identities: &[TokenLayer], layer: LayerId, chunk: &QwenChunkTxn<'_, '_>) -> Result<()> { + for (local, id) in identities.iter().enumerate() { + let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; + id.validate(token, pos, layer)?; + } + Ok(()) +} +impl PromptDeviceQsaState<'_> { + /// The guards after the device completed: the lineage, the step origin and every row identity still hold. + fn recheck( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + context: &Context<'_>, + ) -> Result<()> { cache.validate(binding)?; cache.retained_context(binding, context)?; self.origin.validate(chunk.original_session()?)?; chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; - for (local, id) in self.identities.iter().enumerate() { - let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; - id.validate(token, pos, self.layer)?; - } - Ok(( - block, - PromptDeviceQsaState { - binding: self.binding, - origin: self.origin, - context: self.context, - layer: self.layer, - prior: self.prior, - provider: self.provider, - identities: self.identities, - index, - kv: appended, - }, - )) + check_rows(&self.identities, self.layer, chunk) } -} -impl PromptDeviceQsaState<'_> { /// Genuine chronological current transaction, true previous native prior, /// actual prefix after this row and actual completed INT8 snapshot. The /// whole final state is never relabelled as an earlier row's state. 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 d9cefae2..5a11c06f 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 @@ -3,7 +3,7 @@ #![allow(dead_code)] use super::{ contract::{Error, LayerId, Result}, - dense_weight_cache::DenseWeightCache, + dense_weight_cache::{DenseWeightCache, QsaResident}, gr::ResidualReady, qsa_index::{QsaPrior, validate_values}, qsa_prefill_batch::NativeProjectionRow, @@ -35,49 +35,103 @@ pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> { gate: Box<[f32]>, selected: QsaPromptSelection<'lease, 'ctx>, } -#[allow(clippy::too_many_arguments)] // Actual whole chunk/current prior and admitted fixed owners. -pub(super) fn prepare<'source, 'lease, 'ctx>( +/// Host images of one prompt chunk, filled row by row from the native projections. +struct PromptHost { + raw: Vec, + k: Vec, + v: Vec, + qfull: Vec, + iq: Vec, + gate: Vec, +} +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() }; + for (x, n) in [ + (&mut host.raw, t * 128), + (&mut host.k, t * 512), + (&mut host.v, t * 512), + (&mut host.qfull, t * 12288), + (&mut host.iq, t * 512), + (&mut host.gate, t * 6144), + ] { + x.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + } + Ok(host) + } + fn take_rows<'source, 'ctx>( + &mut self, + rows: &mut [NativeProjectionRow<'source, 'ctx>], + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + ) -> Result<()> { + for (local, row) in rows.iter_mut().enumerate() { + self.k.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::K)?); + self.v.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::V)?); + let q = row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::Q)?; + for h in 0..24 { + self.gate.extend_from_slice(&q[h * 512 + 256..h * 512 + 512]); + } + self.qfull.extend_from_slice(&q); + self.raw.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexK)?); + self.iq.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexQ)?); + } + Ok(()) + } + fn validate(&self, t: usize) -> Result<()> { + for (x, n) in [ + (&self.raw, t * 128), + (&self.k, t * 512), + (&self.v, t * 512), + (&self.qfull, t * 12288), + (&self.iq, t * 512), + (&self.gate, t * 6144), + ] { + validate_values(x, n)?; + } + Ok(()) + } + fn append_select<'lease, 'ctx>( + &self, + owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + cache: &DenseWeightCache<'ctx>, + entry: &QsaResident, + prior: &QsaPrior, + (first, t): (u64, usize), + ) -> Result> { + let (pooled, tail, dead) = prior.native_index_image()?; + let gamma = cache.qsa_norms(entry)?; + owner + .append_select( + u32::try_from(first).map_err(|_| Error::InvalidPosition)?, + t as u32, + &pooled, + &tail, + &dead, + &self.raw, + &self.k, + &self.v, + &self.qfull, + &self.iq, + gamma, + workspace, + ) + .map_err(driver) + } +} +/// All original producer/row guards precede role consumption or CUDA writes. +fn collect_sources<'source, 'ctx>( + sources: &mut Vec<&'source ResidualReady>, + rows: &[NativeProjectionRow<'source, 'ctx>], binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, chunk: &QwenChunkTxn<'_, '_>, layer: LayerId, - prior: &QsaPrior, - rows: &mut [NativeProjectionRow<'source, 'ctx>], - owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, -) -> Result> { - let t = rows.len(); - if t == 0 || t > owner.capacity() || t != chunk.micro_len()? { - return Err(Error::InvalidDimension); - } - let context = cache.retained_context(binding, chunk.context()?)?; - // Root's authentic current next_qsa/source-owner fence. No arbitrary prior acceptance. - chunk.validate_prompt_qsa_prior(layer, prior)?; - let entry = cache.qsa(binding, layer.get())?; - let origin = chunk.original_session()?.target_origin()?; - let first = rows[0].source().identity().position().get(); - if prior.next_position() != first { - return Err(Error::InvalidPosition); - } - let mut sources: Vec<&'source ResidualReady> = Vec::new(); - sources.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; - let mut raw = Vec::new(); - let mut k = Vec::new(); - let mut v = Vec::new(); - let mut qfull = Vec::new(); - let mut iq = Vec::new(); - let mut gate = Vec::new(); - for (x, n) in [ - (&mut raw, t * 128), - (&mut k, t * 512), - (&mut v, t * 512), - (&mut qfull, t * 12288), - (&mut iq, t * 512), - (&mut gate, t * 6144), - ] { - x.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; - } - // All original producer/row guards precede role consumption or CUDA writes. + first: u64, +) -> Result<()> { for (local, row) in rows.iter().enumerate() { let source = row.source(); let index = chunk.micro_row_index(local)?; @@ -91,46 +145,83 @@ pub(super) fn prepare<'source, 'lease, 'ctx>( validate_values(source.mixed(), 2560)?; sources.push(source); } - for (local, row) in rows.iter_mut().enumerate() { - k.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::K)?); - v.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::V)?); - let q = row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::Q)?; - for h in 0..24 { - gate.extend_from_slice(&q[h * 512 + 256..h * 512 + 512]); - } - qfull.extend_from_slice(&q); - raw.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexK)?); - iq.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexQ)?); - } - for (x, n) in - [(&raw, t * 128), (&k, t * 512), (&v, t * 512), (&qfull, t * 12288), (&iq, t * 512), (&gate, t * 6144)] - { - validate_values(x, n)?; - } - let (pooled, tail, dead) = prior.native_index_image()?; - let gamma = cache.qsa_norms(entry)?; - let selected = owner - .append_select( - u32::try_from(first).map_err(|_| Error::InvalidPosition)?, - t as u32, - &pooled, - &tail, - &dead, - &raw, - &k, - &v, - &qfull, - &iq, - gamma, - workspace, - ) - .map_err(driver)?; - chunk.validate_prompt_qsa_prior(layer, prior)?; - cache.retained_context(binding, context)?; - origin.validate(chunk.original_session()?)?; + Ok(()) +} +fn validate_sources(chunk: &QwenChunkTxn<'_, '_>, layer: LayerId, sources: &[&ResidualReady]) -> Result<()> { for (local, source) in sources.iter().enumerate() { chunk.validate_attention_input(chunk.micro_row_index(local)?, layer, source)?; } + Ok(()) +} +/// The completed result wins when it failed; when it succeeded, the health check after it decides. +fn primary_or_health(result: Result, health: Result<()>) -> Result { + match result { + Err(primary) => Err(primary), + Ok(value) => { + health?; + Ok(value) + } + } +} +/// The guards of `prepare` before any role is consumed: capacity, lineage and the first position of the chunk. +fn index_guards<'c, 'ctx>( + binding: &ModelBinding, + cache: &'c DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + (layer, prior): (LayerId, &QsaPrior), + (rows, capacity): (&[NativeProjectionRow<'_, 'ctx>], usize), +) -> Result<(&'ctx Context<'ctx>, &'c QsaResident, TargetStepOrigin, u64)> { + let t = rows.len(); + if t == 0 || t > capacity || t != chunk.micro_len()? { + return Err(Error::InvalidDimension); + } + let context = cache.retained_context(binding, chunk.context()?)?; + // Root's authentic current next_qsa/source-owner fence. No arbitrary prior acceptance. + chunk.validate_prompt_qsa_prior(layer, prior)?; + let entry = cache.qsa(binding, layer.get())?; + let origin = chunk.original_session()?.target_origin()?; + let first = rows[0].source().identity().position().get(); + if prior.next_position() != first { + return Err(Error::InvalidPosition); + } + Ok((context, entry, origin, first)) +} +/// The source rows of the chunk and the host images taken from their native projections. +fn gather_prompt<'source, 'ctx>( + rows: &mut [NativeProjectionRow<'source, 'ctx>], + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + (layer, first): (LayerId, u64), +) -> Result<(Vec<&'source ResidualReady>, PromptHost)> { + let t = rows.len(); + let mut sources: Vec<&'source ResidualReady> = Vec::new(); + sources.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + let mut host = PromptHost::reserve(t)?; + collect_sources(&mut sources, rows, binding, chunk, layer, first)?; + host.take_rows(rows, binding, cache, chunk, layer)?; + 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<'_, '_>, + layer: LayerId, + prior: &QsaPrior, + rows: &mut [NativeProjectionRow<'source, 'ctx>], + owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let (context, entry, origin, first) = + index_guards(binding, cache, chunk, (layer, prior), (rows, 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()))?; + chunk.validate_prompt_qsa_prior(layer, prior)?; + cache.retained_context(binding, context)?; + origin.validate(chunk.original_session()?)?; + validate_sources(chunk, layer, &sources)?; Ok(PromptIndexBatch { binding: binding.identity(), origin, @@ -139,7 +230,7 @@ pub(super) fn prepare<'source, 'lease, 'ctx>( prior: prior.clone(), provider: entry.weights.clone(), sources, - gate: gate.into_boxed_slice(), + gate: host.gate.into_boxed_slice(), selected, }) } @@ -193,21 +284,12 @@ impl<'source, 'lease, 'ctx> PromptIndexBatch<'source, 'lease, 'ctx> { ) -> Result { self.validate(binding, cache, chunk)?; chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; - for (local, source) in self.sources.iter().enumerate() { - chunk.validate_attention_input(chunk.micro_row_index(local)?, self.layer, source)?; - } + validate_sources(chunk, self.layer, &self.sources)?; let result = self .selected .with_completed_kv(|k, v| self.selected.with_completed_buffers(|q, ids, steps| Ok(f(k, v, q, ids, steps)))) .map_err(driver)?; - let health = self.validate(binding, cache, chunk); - match result { - Err(primary) => Err(primary), - Ok(value) => { - health?; - Ok(value) - } - } + primary_or_health(result, self.validate(binding, cache, chunk)) } pub(super) fn with_completed_after_causal( &self, @@ -221,24 +303,16 @@ impl<'source, 'lease, 'ctx> PromptIndexBatch<'source, 'lease, 'ctx> { if proofs.len() != self.rows() { return Err(Error::InvalidDimension); } + self.validate_proofs(chunk, proofs)?; + let result = self.selected.with_completed_buffers(|q, ids, steps| Ok(f(q, ids, steps))).map_err(driver)?; + let health = self.validate(binding, cache, chunk).and_then(|()| self.validate_proofs(chunk, proofs)); + primary_or_health(result, health) + } + fn validate_proofs(&self, chunk: &QwenChunkTxn<'_, '_>, proofs: &[PreparedLayerRow]) -> Result<()> { for (proof, source) in proofs.iter().zip(&self.sources) { chunk.validate_prepared_attention_input(proof, source)?; } - let result = self.selected.with_completed_buffers(|q, ids, steps| Ok(f(q, ids, steps))).map_err(driver)?; - let health: Result<()> = (|| { - self.validate(binding, cache, chunk)?; - for (proof, source) in proofs.iter().zip(&self.sources) { - chunk.validate_prepared_attention_input(proof, source)?; - } - Ok(()) - })(); - match result { - Err(primary) => Err(primary), - Ok(value) => { - health?; - Ok(value) - } - } + Ok(()) } pub(super) fn prefix_for_txn<'a>( &'a self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs index fff6083a..f209868c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl ResidentQsaCompleted. #[allow(unused_imports)] +use super::impl_residentqsalayer::mint; use super::*; impl<'index, 'weights, 'ctx> ResidentQsaCompleted<'index, 'weights, 'ctx> { @@ -89,15 +90,8 @@ impl<'index, 'weights, 'ctx> ResidentQsaCompleted<'index, 'weights, 'ctx> { cache.validate(binding)?; cache.retained_context(binding, self.context)?; self.origin.validate_projection_branch(session)?; - let next = ResidentQsaPrior(Rc::new(Prior { - binding: self.binding, - owner: self.prior.0.owner.clone(), - origin: self.origin, - layer: self.layer, - provider: self.provider, - index, - kv, - })); + let next = + mint(self.binding, self.prior.0.owner.clone(), self.origin, (self.layer, self.provider), (index, kv)); Ok(ResidentQsaSeal { context: self.context, previous: self.prior, next, accepted }) } pub(in crate::qwen_forward) fn abort( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs index 95c58197..c82c74b0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs @@ -10,7 +10,7 @@ impl<'ctx> ResidentQsaLayer<'ctx> { cache: &DenseWeightCache<'ctx>, session: &QwenSession<'ctx>, empty: &QsaPrior, - index: OriginalQsaResidentIndex<'ctx>, + mut index: OriginalQsaResidentIndex<'ctx>, kv: OriginalQsaMappedJournal<'ctx>, ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result { @@ -18,28 +18,14 @@ impl<'ctx> ResidentQsaLayer<'ctx> { let origin = session.target_origin()?; let context = cache.retained_context(binding, session.mtp_context()?)?; cache.validate(binding)?; - if !empty.0.binding.matches(&binding.identity()) - || empty.next_position() != 0 - || index.next_position() != 0 - || kv.next_position() != 0 - { - return Err(Error::IdentityMismatch); - } + check_empty(binding, empty, &index, &kv)?; index.validate_context(context).map_err(device_error)?; kv.validate_context(context).map_err(device_error)?; let entry = cache.qsa(binding, empty.layer().get())?; - let mut index = index; let saved = index.checkpoint(ws).map_err(device_error)?; let prefix = kv.empty_prefix().map_err(device_error)?; - let current = ResidentQsaPrior(Rc::new(Prior { - binding: binding.identity(), - owner: empty.0.owner.clone(), - origin, - layer: empty.layer(), - provider: entry.weights.clone(), - index: saved, - kv: prefix, - })); + let owner = empty.0.owner.clone(); + let current = mint(binding.identity(), owner, origin, (empty.layer(), entry.weights.clone()), (saved, prefix)); Ok(Self { context, index, kv, current }) } pub(in crate::qwen_forward) fn current(&self) -> ResidentQsaPrior<'ctx> { @@ -81,6 +67,29 @@ impl<'ctx> ResidentQsaLayer<'ctx> { ) -> Result<()> { self.kv.begin_stage_prefix(ws, stage, &prior.0.kv, read).map_err(device_error) } + /// The pre-device guards of `prepare`: the layer, the step origin, and one identity per input row. + fn begin_prepare( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + inputs: &[&InputReady], + prior: &ResidentQsaPrior<'ctx>, + read: &OriginalDeviceGrRead<'_, '_, 'ctx>, + ) -> Result<(TargetStepOrigin, LayerId, Vec)> { + self.validate(binding, cache, session, prior)?; + let origin = session.target_origin()?; + let layer = prior.layer(); + if inputs.is_empty() + || inputs.len() > 8192 + || read.rows() != inputs.len() + || !read.context_matches(self.context) + { + return Err(Error::IdentityMismatch); + } + let identities = resident_identities(binding, inputs, prior, layer)?; + Ok((origin, layer, identities)) + } pub(in crate::qwen_forward) fn prepare<'lease, 'index, 'weights, 'arena, 'loan>( &'index mut self, binding: &ModelBinding, @@ -92,61 +101,10 @@ impl<'ctx> ResidentQsaLayer<'ctx> { read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - self.validate(binding, cache, session, prior)?; - let origin = session.target_origin()?; - let layer = prior.layer(); - if inputs.is_empty() - || inputs.len() > 8192 - || read.rows() != inputs.len() - || !read.context_matches(self.context) - { - return Err(Error::IdentityMismatch); - } - let mut identities = Vec::new(); - identities.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; - for (local, input) in inputs.iter().enumerate() { - if !input.binding_identity().matches(&binding.identity()) - || input.position().get() != prior.next_position().checked_add(local as u64).ok_or(Error::Overflow)? - { - return Err(Error::IdentityMismatch); - } - identities.push(TokenLayer::new(input.token(), input.position(), layer)); - } + let (origin, layer, identities) = self.begin_prepare(binding, cache, session, inputs, prior, &read)?; let entry = cache.qsa(binding, layer.get())?; - for (role, n, k) in [ - (QsaMatrixRole::K, 512, 2560), - (QsaMatrixRole::V, 512, 2560), - (QsaMatrixRole::Q, 12288, 2560), - (QsaMatrixRole::IndexK, 128, 2560), - (QsaMatrixRole::IndexQ, 512, 2560), - (QsaMatrixRole::Out, 2560, 6144), - ] { - if entry.weights.shape(role) != (k, n) { - return Err(Error::InvalidDimension); - } - } - let (k, kk) = cache.qsa_matrix(entry, ROLES[0])?; - let (v, vk) = cache.qsa_matrix(entry, ROLES[1])?; - let (q, qk) = cache.qsa_matrix(entry, ROLES[2])?; - let (ik, ikk) = cache.qsa_matrix(entry, ROLES[3])?; - let (iq, iqk) = cache.qsa_matrix(entry, ROLES[4])?; - let (out, ok) = cache.qsa_matrix(entry, ROLES[5])?; - if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { - return Err(Error::Unsupported(Stage::QsaIndex)); - } - let selected = producer - .prepare( - read, - ws, - &mut self.index, - &prior.0.index, - OriginalQsaPromptWeights { - projections: [k, v, q, ik, iq, out], - kinds: [native(kk)?, native(vk)?, native(qk)?, native(ok)?], - norms: cache.qsa_norms(entry)?, - }, - ) - .map_err(device_error)?; + let weights = resident_weights(cache, entry)?; + let selected = producer.prepare(read, ws, &mut self.index, &prior.0.index, weights).map_err(device_error)?; origin.validate(session)?; cache.validate(binding)?; Ok(ResidentQsaSelection { @@ -226,15 +184,75 @@ impl<'ctx> ResidentQsaLayer<'ctx> { let kv = self.kv.rollback(ws, &prior.0.kv).map_err(device_error); index?; kv?; - self.current = ResidentQsaPrior(Rc::new(Prior { - binding: prior.0.binding.clone(), - owner: prior.0.owner.clone(), - origin, - layer: prior.layer(), - provider: prior.0.provider.clone(), - index: prior.0.index.clone(), - kv: prior.0.kv.clone(), - })); + self.current = rehome(&prior.0, origin, (prior.0.index.clone(), prior.0.kv.clone())); Ok(self.current.clone()) } } + +/// The empty-lineage fence of `ResidentQsaLayer::new`: nothing has been appended yet. +fn check_empty( + binding: &ModelBinding, + empty: &QsaPrior, + index: &OriginalQsaResidentIndex<'_>, + kv: &OriginalQsaMappedJournal<'_>, +) -> Result<()> { + if !empty.0.binding.matches(&binding.identity()) + || empty.next_position() != 0 + || index.next_position() != 0 + || kv.next_position() != 0 + { + return Err(Error::IdentityMismatch); + } + Ok(()) +} +/// A fresh lineage witness over the given device checkpoint and mapped prefix. +pub(super) fn mint<'ctx>( + binding: BindingIdentity, + owner: QsaOwner, + origin: TargetStepOrigin, + (layer, provider): (LayerId, Rc), + (index, kv): (OriginalQsaIndexCheckpoint<'ctx>, OriginalQsaMappedPrefix), +) -> ResidentQsaPrior<'ctx> { + ResidentQsaPrior(Rc::new(Prior { binding, owner, origin, layer, provider, index, kv })) +} +/// The lineage of `base` re-homed to `origin` over the given device checkpoint and mapped prefix. +pub(super) fn rehome<'ctx>( + base: &Prior<'ctx>, + origin: TargetStepOrigin, + device: (OriginalQsaIndexCheckpoint<'ctx>, OriginalQsaMappedPrefix), +) -> ResidentQsaPrior<'ctx> { + let (binding, owner) = (base.binding.clone(), base.owner.clone()); + mint(binding, owner, origin, (base.layer, base.provider.clone()), device) +} +/// One identity per input row, each at the position right after the prior's end. +fn resident_identities( + binding: &ModelBinding, + inputs: &[&InputReady], + prior: &ResidentQsaPrior<'_>, + layer: LayerId, +) -> Result> { + let mut identities = Vec::new(); + identities.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; + for (local, input) in inputs.iter().enumerate() { + if !input.binding_identity().matches(&binding.identity()) + || input.position().get() != prior.next_position().checked_add(local as u64).ok_or(Error::Overflow)? + { + return Err(Error::IdentityMismatch); + } + identities.push(TokenLayer::new(input.token(), input.position(), layer)); + } + Ok(identities) +} +/// The projection buffers and native kinds of one layer's QSA weights; the kinds are converted after the buffers. +fn resident_weights<'a, 'ctx>( + cache: &'a DenseWeightCache<'ctx>, + entry: &QsaResident, +) -> Result> { + check_prompt_shapes(entry)?; + let (projections, [kk, vk, qk, ok]) = prompt_projections(cache, entry)?; + Ok(OriginalQsaPromptWeights { + projections, + kinds: [native(kk)?, native(vk)?, native(qk)?, native(ok)?], + norms: cache.qsa_norms(entry)?, + }) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs index d9e2b9aa..456bdebf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs @@ -1,14 +1,16 @@ //! Moved out of the parent module by STRA-338: impl ResidentQsaLayer (2), impl ResidentQsaPublication, impl ResidentQsaSeal, impl ResidentQsaSelection, impl ResidentQsaRow. #[allow(unused_imports)] +use super::impl_residentqsalayer::rehome; use super::*; impl<'ctx> ResidentQsaLayer<'ctx> { /// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index /// rows). `first` and `tokens` are multiples of four and lie below the layer's end. pub(in crate::qwen_forward) fn export_span(&self, first: usize, tokens: usize) -> Result { - // `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover its cells, and only the - // complete 4-cell rows of the index image are copied (the checkpoint's tail carries the partial one) + // `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover + // its cells, and only the complete 4-cell rows of the index image are copied (the checkpoint's tail carries + // the partial one) if first % 4 != 0 || tokens == 0 || first + tokens > self.current.next_position() as usize { return Err(Error::InvalidPosition); } @@ -47,9 +49,7 @@ impl<'ctx> ResidentQsaLayer<'ctx> { if !std::ptr::eq(context, self.context) || !self.current.0.binding.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } - let index_spans: Vec<(usize, &[u8])> = - spans.iter().filter(|s| !s.index.is_empty()).map(|s| (s.first_token / 4, &s.index[..])).collect(); - let kv_spans: Vec<(usize, &[u8])> = spans.iter().map(|s| (s.first_token / 4, &s.kv[..])).collect(); + let (index_spans, kv_spans) = span_views(spans); let index = { let _p = crate::qwen_forward::original_serve_profile::span("prefix.layer_index"); self.index.import(ws, &index_spans, tail, end).map_err(device_error) @@ -59,15 +59,7 @@ impl<'ctx> ResidentQsaLayer<'ctx> { self.kv.import_pages(ws, &kv_spans, end).map_err(device_error) }; let (index, kv) = (index?, kv?); - self.current = ResidentQsaPrior(Rc::new(Prior { - binding: self.current.0.binding.clone(), - owner: self.current.0.owner.clone(), - origin, - layer: self.current.layer(), - provider: self.current.0.provider.clone(), - index, - kv, - })); + self.current = rehome(&self.current.0, origin, (index, kv)); Ok(self.current.clone()) } /// One-way handoff into the native verifier. It moves the same resident @@ -182,13 +174,31 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> } pub(in crate::qwen_forward) fn complete( self, - binding: &ModelBinding, + model: &ModelBinding, cache: &DenseWeightCache<'ctx>, session: &QwenSession<'ctx>, ws: &mut NativeBatchWorkspace<'ctx>, stage: &mut OriginalQsaResidentTransport<'ctx>, attention: &mut OriginalQsaResidentAttention<'ctx>, ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, ResidentQsaCompleted<'index, 'weights, 'ctx>)> { + let (ctx, out, kind) = self.check_inputs(model, cache, session)?; + let Self { binding, origin, context, layer, prior, provider, identities, selected, kv } = self; + let (block, index, appended) = + selected.complete(ws, kv, stage, &prior.0.kv, attention, out, kind).map_err(device_error)?; + origin.validate(session)?; + cache.validate(model)?; + cache.retained_context(model, ctx)?; + let done = + ResidentQsaCompleted { binding, origin, context, layer, prior, provider, identities, index, kv, appended }; + Ok((block, done)) + } + /// The guards before the device completes: origin, binding, context and weights lineage, and the `Out` matrix. + fn check_inputs<'c>( + &self, + binding: &ModelBinding, + cache: &'c DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + ) -> Result<(&'ctx Context<'ctx>, &'c DeviceBuffer<'ctx>, QsaNativeKind)> { self.origin.validate(session)?; cache.validate(binding)?; let context = cache.retained_context(binding, session.mtp_context()?)?; @@ -200,28 +210,7 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> return Err(Error::IdentityMismatch); } let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; - let (block, index, appended) = self - .selected - .complete(ws, self.kv, stage, &self.prior.0.kv, attention, out, native(kind)?) - .map_err(device_error)?; - self.origin.validate(session)?; - cache.validate(binding)?; - cache.retained_context(binding, context)?; - Ok(( - block, - ResidentQsaCompleted { - binding: self.binding, - origin: self.origin, - context: self.context, - layer: self.layer, - prior: self.prior, - provider: self.provider, - identities: self.identities, - index, - kv: self.kv, - appended, - }, - )) + Ok((context, out, native(kind)?)) } } impl ResidentQsaRow<'_, '_> { @@ -232,3 +221,10 @@ impl ResidentQsaRow<'_, '_> { self.kv.next_position() } } + +type SpanViews<'a> = Vec<(usize, &'a [u8])>; +/// The index and K/V byte views of parked spans, keyed by their first four-cell row. +fn span_views<'a>(spans: &[&'a ParkedLayerSpan]) -> (SpanViews<'a>, SpanViews<'a>) { + let index = spans.iter().filter(|s| !s.index.is_empty()).map(|s| (s.first_token / 4, &s.index[..])).collect(); + (index, spans.iter().map(|s| (s.first_token / 4, &s.kv[..])).collect()) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs index 958dc2a2..feed31fe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs @@ -1,5 +1,6 @@ //! Genuine current scalar target/MTP continuation of the same live resident //! layer. Old scalar projection/gate/Out math is retained; no index/page image. +use super::impl_residentqsalayer::mint; use super::*; use leleka_cuda_driver::{ OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, QsaAttentionInputs, QsaNativeDecode, @@ -31,7 +32,130 @@ pub(in crate::qwen_forward) struct ResidentQsaScalarReady<'source, 'ctx> { values: Box<[f32]>, seal: ResidentQsaSeal<'ctx>, } +/// The attention, transport and gate owners of one scalar row. +type ScalarOwners<'a, 'ctx> = + (&'a mut QsaNativeDecode<'ctx>, &'a mut OriginalQsaResidentTransport<'ctx>, &'a mut QsaNativeGate<'ctx>); +/// The five host projections of one input row and the head-gate slice of the full Q. +struct ScalarHost { + raw: Box<[f32]>, + k: Box<[f32]>, + v: Box<[f32]>, + qfull: Box<[f32]>, + iq: Box<[f32]>, + gate: Box<[f32]>, +} +impl ScalarHost { + fn gather( + context: &Context<'_>, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + entry: &QsaResident, + input: &ResidualReady, + ) -> Result { + let at = |role| project(context, binding, &entry.weights, role, input.mixed(), Some(cache)); + let raw = at(QsaMatrixRole::IndexK)?; + let k = at(QsaMatrixRole::K)?; + let v = at(QsaMatrixRole::V)?; + let qfull = at(QsaMatrixRole::Q)?; + let iq = at(QsaMatrixRole::IndexQ)?; + for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] { + validate_values(values, n)?; + } + let gate = scalar_gate(&qfull)?; + Ok(Self { raw, k, v, qfull, iq, gate }) + } + fn select<'lease, 'index, 'weights, 'ctx>( + &self, + owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>, + (resident, prior): (&'index mut OriginalQsaResidentIndex<'ctx>, &OriginalQsaIndexCheckpoint<'ctx>), + norms: [&'weights DeviceBuffer<'ctx>; 4], + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + owner + .prepare(resident, prior, &self.raw, &self.k, &self.v, &self.qfull, &self.iq, norms, workspace) + .map_err(driver) + } +} +fn scalar_gate(qfull: &[f32]) -> Result> { + let mut gate = Vec::new(); + gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?; + for head in 0..24 { + gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]); + } + validate_values(&gate, 6144)?; + Ok(gate.into_boxed_slice()) +} +fn check_txn_input(txn: &QwenStepTxn<'_, '_>, binding: &ModelBinding, input: &ResidualReady) -> Result<()> { + txn.validate_binding(&binding.identity())?; + txn.validate_input(input.identity().token(), input.identity().position()) +} +fn check_scalar_txn( + txn: &QwenStepTxn<'_, '_>, + binding: &ModelBinding, + input: &ResidualReady, + layer: LayerId, + prior: &ResidentQsaPrior<'_>, +) -> Result<()> { + check_txn_input(txn, binding, input)?; + input.identity().validate(txn.token(), txn.position(), layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + txn.validate_projection_branch(&prior.0.origin) +} +fn check_scalar_shapes(entry: &QsaResident) -> Result<()> { + for (role, width) in [ + (QsaMatrixRole::IndexK, 128), + (QsaMatrixRole::K, 512), + (QsaMatrixRole::V, 512), + (QsaMatrixRole::Q, 12288), + (QsaMatrixRole::IndexQ, 512), + ] { + if entry.weights.shape(role) != (2560, width) { + return Err(Error::InvalidDimension); + } + } + Ok(()) +} impl<'ctx> ResidentQsaLayer<'ctx> { + /// The guards of `prepare_scalar` before any projection: the step, the lineage, the weights and the input. + fn scalar_guards<'w>( + &self, + binding: &ModelBinding, + cache: &'w DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + prior: &ResidentQsaPrior<'ctx>, + ) -> Result<(&'ctx Context<'ctx>, &'w QsaResident, Rc<()>)> { + check_scalar_txn(txn, binding, input, layer, prior)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + cache.validate(binding)?; + let entry = cache.qsa(binding, layer.get())?; + self.check_scalar_prior(binding, txn, layer, prior, (context, entry))?; + validate_values(input.mixed(), 2560)?; + check_scalar_shapes(entry)?; + Ok((context, entry, txn.residual_handoff_owner()?)) + } + fn check_scalar_prior( + &self, + binding: &ModelBinding, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + prior: &ResidentQsaPrior<'ctx>, + (context, entry): (&Context<'ctx>, &QsaResident), + ) -> Result<()> { + if !self.current.same_prior(prior) + || layer != prior.layer() + || prior.next_position() != txn.position().get() + || !prior.0.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &prior.0.provider) + { + return Err(Error::IdentityMismatch); + } + self.index.validate_context(context).map_err(driver)?; + self.index.validate_checkpoint(&prior.0.index).map_err(driver)?; + self.kv.validate_prefix(&prior.0.kv).map_err(driver) + } #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn prepare_scalar<'source, 'lease, 'index, 'weights>( &'index mut self, @@ -44,59 +168,11 @@ impl<'ctx> ResidentQsaLayer<'ctx> { owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - txn.validate_binding(&binding.identity())?; - txn.validate_input(input.identity().token(), input.identity().position())?; - input.identity().validate(txn.token(), txn.position(), layer)?; - input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - txn.validate_projection_branch(&prior.0.origin)?; - let context = cache.retained_context(binding, txn.cuda_context()?)?; - cache.validate(binding)?; - let entry = cache.qsa(binding, layer.get())?; - if !self.current.same_prior(prior) - || layer != prior.layer() - || prior.next_position() != txn.position().get() - || !prior.0.binding.matches(&binding.identity()) - || !std::ptr::eq(context, self.context) - || !Rc::ptr_eq(&entry.weights, &prior.0.provider) - { - return Err(Error::IdentityMismatch); - } - self.index.validate_context(context).map_err(driver)?; - self.index.validate_checkpoint(&prior.0.index).map_err(driver)?; - self.kv.validate_prefix(&prior.0.kv).map_err(driver)?; - validate_values(input.mixed(), 2560)?; - for (role, width) in [ - (QsaMatrixRole::IndexK, 128), - (QsaMatrixRole::K, 512), - (QsaMatrixRole::V, 512), - (QsaMatrixRole::Q, 12288), - (QsaMatrixRole::IndexQ, 512), - ] { - if entry.weights.shape(role) != (2560, width) { - return Err(Error::InvalidDimension); - } - } - let transaction = txn.residual_handoff_owner()?; - let raw = project(context, binding, &entry.weights, QsaMatrixRole::IndexK, input.mixed(), Some(cache))?; - let k = project(context, binding, &entry.weights, QsaMatrixRole::K, input.mixed(), Some(cache))?; - let v = project(context, binding, &entry.weights, QsaMatrixRole::V, input.mixed(), Some(cache))?; - let qfull = project(context, binding, &entry.weights, QsaMatrixRole::Q, input.mixed(), Some(cache))?; - let iq = project(context, binding, &entry.weights, QsaMatrixRole::IndexQ, input.mixed(), Some(cache))?; - for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] { - validate_values(values, n)?; - } - let mut gate = Vec::new(); - gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?; - for head in 0..24 { - gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]); - } - validate_values(&gate, 6144)?; - - let selected = owner - .prepare(&mut self.index, &prior.0.index, &raw, &k, &v, &qfull, &iq, cache.qsa_norms(entry)?, workspace) - .map_err(driver)?; - txn.validate_binding(&binding.identity())?; - txn.validate_input(input.identity().token(), input.identity().position())?; + let (context, entry, transaction) = self.scalar_guards(binding, cache, txn, layer, input, prior)?; + let host = ScalarHost::gather(context, binding, cache, entry, input)?; + let norms = cache.qsa_norms(entry)?; + let selected = host.select(owner, (&mut self.index, &prior.0.index), norms, workspace)?; + check_txn_input(txn, binding, input)?; cache.validate(binding)?; Ok(ResidentQsaScalar { binding: binding.identity(), @@ -106,7 +182,7 @@ impl<'ctx> ResidentQsaLayer<'ctx> { prior: prior.clone(), provider: entry.weights.clone(), transaction, - gate: gate.into_boxed_slice(), + gate: host.gate, selected, kv: &mut self.kv, }) @@ -139,6 +215,54 @@ impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, } validate_values(&self.gate, 6144) } + /// The attention of the appended row over the completed buffers. + fn attend( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + attention: &mut QsaNativeDecode<'ctx>, + append: &OriginalQsaMappedAppend, + ) -> Result> { + self.selected + .with_completed_buffers(|q, ids, steps| { + let inputs = QsaAttentionInputs::new(q, ids, steps, 1)?; + let actual = attention.attend_resident(workspace, self.kv, append.final_prefix(), &inputs)?; + actual.into_values() + }) + .map_err(driver) + } + fn gate_out( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + attended: &[f32], + gate_owner: &mut QsaNativeGate<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + let failed = cache.transport_failure_flag(binding, self.context)?; + let provider = self.provider.as_ref(); + gate_and_out(binding, cache, self.context, provider, attended, &self.gate, gate_owner, workspace, &failed) + } + /// The device work of one scalar row: append, attend, gate and Out; the seal or the abort follows. + fn run( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + input: &ResidualReady, + (attention, stage, gate_owner): ScalarOwners<'_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> { + self.validate(binding, cache, txn, input)?; + super::super::admit_budget(self.context)?; + let append = + self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?; + let attended = self.attend(workspace, attention, &append)?; + validate_values(&attended, 6144)?; + let values = self.gate_out(binding, cache, &attended, gate_owner, workspace)?; + self.validate(binding, cache, txn, input)?; + validate_values(&values, 2560)?; + Ok((values, append)) + } #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn complete( mut self, @@ -151,74 +275,37 @@ impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, gate_owner: &mut QsaNativeGate<'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - let operation = (|| -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> { - self.validate(binding, cache, txn, input)?; - super::super::admit_budget(self.context)?; - let append = - self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?; - let attended = self - .selected - .with_completed_buffers(|q, ids, steps| { - let inputs = QsaAttentionInputs::new(q, ids, steps, 1)?; - let actual = attention.attend_resident(workspace, self.kv, append.final_prefix(), &inputs)?; - actual.into_values() - }) - .map_err(driver)?; - validate_values(&attended, 6144)?; - let failed = cache.transport_failure_flag(binding, self.context)?; - let values = gate_and_out( - binding, - cache, - self.context, - self.provider.as_ref(), - &attended, - &self.gate, - gate_owner, - workspace, - &failed, - )?; - self.validate(binding, cache, txn, input)?; - validate_values(&values, 2560)?; - Ok((values, append)) - })(); - match operation { + match self.run(binding, cache, txn, input, (attention, stage, gate_owner), workspace) { Err(primary) => { let index = self.selected.abort(workspace).map_err(driver); let kv = self.kv.rollback(workspace, &self.prior.0.kv).map_err(driver); let _ = (index, kv); Err(primary) } - Ok((values, append)) => { - let index = self.selected.seal(workspace, 1).map_err(driver); - let kv = self.kv.accept_prefix(workspace, &append, 1).map_err(driver); - let index = index?; - let kv = kv?; - cache.validate(binding)?; - cache.retained_context(binding, self.context)?; - txn.validate_projection_branch(&self.prior.0.origin)?; - let next = ResidentQsaPrior(Rc::new(Prior { - binding: self.binding.clone(), - owner: self.prior.0.owner.clone(), - origin: self.prior.0.origin.clone(), - layer: self.layer, - provider: self.provider.clone(), - index, - kv, - })); - let seal = ResidentQsaSeal { context: self.context, previous: self.prior, next, accepted: 1 }; - Ok(ResidentQsaScalarReady { - binding: self.binding, - context: self.context, - layer: self.layer, - source: self.source, - provider: self.provider, - transaction: self.transaction, - values, - seal, - }) - } + Ok((values, append)) => self.seal_ready(binding, cache, txn, workspace, (values, append)), } } + fn seal_ready( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + (values, append): (Box<[f32]>, OriginalQsaMappedAppend), + ) -> Result> { + let Self { binding: id, context, layer, source, prior, provider, transaction, selected, kv: journal, .. } = + self; + let index = selected.seal(workspace, 1).map_err(driver); + let kv = journal.accept_prefix(workspace, &append, 1).map_err(driver); + let (index, kv) = (index?, kv?); + cache.validate(binding)?; + cache.retained_context(binding, context)?; + txn.validate_projection_branch(&prior.0.origin)?; + let (owner, origin) = (prior.0.owner.clone(), prior.0.origin.clone()); + let next = mint(id.clone(), owner, origin, (layer, provider.clone()), (index, kv)); + let seal = ResidentQsaSeal { context, previous: prior, next, accepted: 1 }; + Ok(ResidentQsaScalarReady { binding: id, context, layer, source, provider, transaction, values, seal }) + } } impl<'source, 'ctx> ResidentQsaScalarReady<'source, 'ctx> { pub(in crate::qwen_forward) fn into_parts( @@ -247,6 +334,81 @@ impl<'source, 'ctx> ResidentQsaScalarReady<'source, 'ctx> { Ok((input.identity(), self.values, self.seal)) } } +/// The role buffers of one gate-and-Out run: attended, gate, gated, Out. +type GateBuffers<'ctx> = [Option>; 4]; +fn upload_gate_inputs<'ctx>( + buffers: &mut GateBuffers<'ctx>, + context: &'ctx Context<'ctx>, + (attended, gate): (&[f32], &[f32]), + failed: &Cell, +) -> Result<()> { + if failed.get() { + return Err(Error::CudaExecution); + } + validate_values(attended, 6144)?; + validate_values(gate, 6144)?; + buffers[0] = Some(upload(context, attended)?); + buffers[1] = Some(upload(context, gate)?); + buffers[2] = Some(allocate(context, 6144)?); + Ok(()) +} +fn apply_gate<'ctx>( + buffers: &mut GateBuffers<'ctx>, + owner: &mut QsaNativeGate<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result<()> { + let (inputs, outputs) = buffers.split_at_mut(2); + owner + .apply( + workspace, + inputs[0].as_ref().ok_or(Error::IdentityMismatch)?, + inputs[1].as_ref().ok_or(Error::IdentityMismatch)?, + outputs[0].as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver) +} +fn project_gated_out<'ctx>( + buffers: &mut GateBuffers<'ctx>, + (binding, cache): (&ModelBinding, &DenseWeightCache<'ctx>), + context: &'ctx Context<'ctx>, + weights: &QsaWeights, +) -> Result> { + // Entire attended tensor was finite before gate, and entire gated result + // is finite BEFORE acquiring Out, so a later projection cannot mask it. + let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?; + validate_values(&gated, 6144)?; + let entry = cache.qsa(binding, weights.layer())?; + if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) { + return Err(Error::IdentityMismatch); + } + let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; + // This selected literal native profile only has Original quantized kinds; + // BF16 must not silently become a different decode arithmetic fallback. + if kind == QsaMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::QsaIndex)); + } + buffers[3] = Some(allocate(context, 2560)?); + let (inputs, outputs) = buffers.split_at_mut(3); + project_scratch_out_numeric( + context, + matrix, + inputs[2].as_ref().ok_or(Error::IdentityMismatch)?, + outputs[0].as_mut().ok_or(Error::IdentityMismatch)?, + kind, + ) +} +/// Release every role buffer; the first release failure is the one returned. +fn release_gate_buffers(buffers: GateBuffers<'_>) -> Result<()> { + let mut cleanup = Ok(()); + for buffer in buffers.into_iter().flatten() { + if let Err(error) = buffer.release().map_err(driver) { + if cleanup.is_ok() { + cleanup = Err(error); + } + } + } + cleanup +} #[allow(clippy::too_many_arguments)] // Actual role-specific weights and closed current finite inputs. fn gate_and_out<'ctx>( binding: &ModelBinding, @@ -259,59 +421,13 @@ fn gate_and_out<'ctx>( workspace: &mut NativeBatchWorkspace<'ctx>, failed: &Cell, ) -> Result> { - let mut buffers: [Option>; 4] = std::array::from_fn(|_| None); + let mut buffers: GateBuffers<'ctx> = std::array::from_fn(|_| None); let operation = (|| { - if failed.get() { - return Err(Error::CudaExecution); - } - validate_values(attended, 6144)?; - validate_values(gate, 6144)?; - buffers[0] = Some(upload(context, attended)?); - buffers[1] = Some(upload(context, gate)?); - buffers[2] = Some(allocate(context, 6144)?); - { - let (inputs, outputs) = buffers.split_at_mut(2); - owner - .apply( - workspace, - inputs[0].as_ref().ok_or(Error::IdentityMismatch)?, - inputs[1].as_ref().ok_or(Error::IdentityMismatch)?, - outputs[0].as_mut().ok_or(Error::IdentityMismatch)?, - ) - .map_err(driver)?; - } - // Entire attended tensor was finite before gate, and entire gated result - // is finite BEFORE acquiring Out, so a later projection cannot mask it. - let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?; - validate_values(&gated, 6144)?; - let entry = cache.qsa(binding, weights.layer())?; - if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) { - return Err(Error::IdentityMismatch); - } - let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; - // This selected literal native profile only has Original quantized kinds; - // BF16 must not silently become a different decode arithmetic fallback. - if kind == QsaMatrixKind::Bf16 { - return Err(Error::Unsupported(Stage::QsaIndex)); - } - buffers[3] = Some(allocate(context, 2560)?); - let (inputs, outputs) = buffers.split_at_mut(3); - project_scratch_out_numeric( - context, - matrix, - inputs[2].as_ref().ok_or(Error::IdentityMismatch)?, - outputs[0].as_mut().ok_or(Error::IdentityMismatch)?, - kind, - ) + upload_gate_inputs(&mut buffers, context, (attended, gate), failed)?; + apply_gate(&mut buffers, owner, workspace)?; + project_gated_out(&mut buffers, (binding, cache), context, weights) })(); - let mut cleanup = Ok(()); - for buffer in buffers.into_iter().flatten() { - if let Err(error) = buffer.release().map_err(driver) { - if cleanup.is_ok() { - cleanup = Err(error); - } - } - } + let cleanup = release_gate_buffers(buffers); if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() { failed.set(true); } 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 3bc42001..658e4240 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 @@ -55,22 +55,31 @@ struct Plan { selected: Vec, } -// Entire plan, protected-hit set and miss payload are prepared before any device write. -// The candidate carries real binding/session/layer authority; ids are actual causal selection. -fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { - prior.validate_extent()?; - validate_ids(ids, prior.next_position())?; - let mut next = old.copy_for(&prior.0.owner)?; +impl LayerDirectory { + /// Record the new cell at `slot` and advance the cursor behind it. + fn install(&mut self, slot: usize, page: &Rc, offset: u8) { + self.cells[slot] = Some(CachedCell { page: Rc::downgrade(page), offset }); + self.index.insert((Rc::as_ptr(page) as usize, offset), slot); + self.cursor = (slot + 1) % SLOTS; + } +} +fn filled(len: usize, value: T) -> Result> { + let mut values = reserve(len)?; + values.resize(len, value); + Ok(values) +} +/// One live page reference and cell offset per selected id. +fn plan_sources(prior: &QsaPrior, ids: &[i32]) -> Result, u8)>> { let mut sources = reserve(ids.len())?; for &id in ids { let cell = usize::try_from(id).map_err(|_| Error::InvalidPosition)?; let page = prior.0.pages.get(cell / 4).ok_or(Error::InvalidPosition)?; sources.push((page.clone(), (cell % 4) as u8)); } - let mut protected = reserve(SLOTS)?; - protected.resize(SLOTS, false); - let mut selected = reserve(ids.len())?; - selected.resize(ids.len(), u32::MAX); + Ok(sources) +} +/// Rows whose cell is already resident are protected from eviction and select their slot. +fn mark_hits(next: &LayerDirectory, sources: &[(Rc, u8)], protected: &mut [bool], selected: &mut [u32]) { for (row, (page, offset)) in sources.iter().enumerate() { let key = (Rc::as_ptr(page) as usize, *offset); if let Some(&slot) = next.index.get(&key) @@ -80,38 +89,54 @@ fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { selected[row] = slot as u32; } } +} +/// The next unprotected slot after the cursor, with its previous occupant evicted from the index. +fn claim_slot(next: &mut LayerDirectory, protected: &[bool]) -> Result { + let slot = (0..SLOTS) + .map(|step| (next.cursor + step) % SLOTS) + .find(|&slot| !protected[slot]) + .ok_or(Error::InvalidDimension)?; + if let Some(old) = next.cells[slot].take() + && next.index.get(&old.key()) == Some(&slot) + { + next.index.remove(&old.key()); + } + Ok(slot) +} +/// Preserve exact cell/head order and validate both FP16 domains before upload. +fn copy_cell(page: &KvPage, offset: u8, k: &mut Vec, v: &mut Vec) -> Result<()> { + for head in 0..2 { + let start = (head * 4 + usize::from(offset)) * 256; + for i in start..start + 256 { + validate_half(page.k[i])?; + validate_half(page.v[i])?; + k.extend_from_slice(&page.k[i].to_le_bytes()); + v.extend_from_slice(&page.v[i].to_le_bytes()); + } + } + Ok(()) +} +// Entire plan, protected-hit set and miss payload are prepared before any device write. +// The candidate carries real binding/session/layer authority; ids are actual causal selection. +fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { + prior.validate_extent()?; + validate_ids(ids, prior.next_position())?; + let mut next = old.copy_for(&prior.0.owner)?; + let sources = plan_sources(prior, ids)?; + let mut protected = filled(SLOTS, false)?; + let mut selected = filled(ids.len(), u32::MAX)?; + mark_hits(&next, &sources, &mut protected, &mut selected); let miss_count = selected.iter().filter(|&&slot| slot == u32::MAX).count(); let mut misses = reserve(miss_count)?; let bytes = miss_count.checked_mul(CELL_BYTES).ok_or(Error::Overflow)?; - let mut k = reserve(bytes)?; - let mut v = reserve(bytes)?; + let (mut k, mut v) = (reserve(bytes)?, reserve(bytes)?); for (row, (page, offset)) in sources.iter().enumerate() { if selected[row] != u32::MAX { continue; } - let slot = (0..SLOTS) - .map(|step| (next.cursor + step) % SLOTS) - .find(|&slot| !protected[slot]) - .ok_or(Error::InvalidDimension)?; - if let Some(old) = next.cells[slot].take() - && next.index.get(&old.key()) == Some(&slot) - { - next.index.remove(&old.key()); - } - // Preserve exact cell/head order and validate both FP16 domains before upload. - for head in 0..2 { - let start = (head * 4 + usize::from(*offset)) * 256; - for i in start..start + 256 { - validate_half(page.k[i])?; - validate_half(page.v[i])?; - k.extend_from_slice(&page.k[i].to_le_bytes()); - v.extend_from_slice(&page.v[i].to_le_bytes()); - } - } - let key = (Rc::as_ptr(page) as usize, *offset); - next.cells[slot] = Some(CachedCell { page: Rc::downgrade(page), offset: *offset }); - next.index.insert(key, slot); - next.cursor = (slot + 1) % SLOTS; + let slot = claim_slot(&mut next, &protected)?; + copy_cell(page, *offset, &mut k, &mut v)?; + next.install(slot, page, *offset); protected[slot] = true; selected[row] = slot as u32; misses.push(slot as u32); @@ -126,56 +151,62 @@ pub(in crate::qwen_forward) struct QsaSelectedCache<'ctx> { layers: [LayerDirectory; 12], workspace: Option>, } +/// A driver failure on the context: a poisoned context also marks the cache failed. +fn context_failure(context: &Context<'_>, failed: &Cell, error: leleka_cuda_driver::Error) -> Error { + if context.is_poisoned() { + failed.set(true); + } + driver_error(error) +} +/// The workspace plus the peak of the device scratch must fit the budget and the free device memory. +fn admit_workspace(context: &Context<'_>, failed: &Cell) -> Result<()> { + if failed.get() || context.is_poisoned() { + return Err(Error::CudaExecution); + } + let required = WORKSPACE_BYTES.checked_add(device_peak()).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(required).is_none_or(|bytes| bytes > context.budget_bytes()) { + return Err(Error::InputAllocation); + } + let (free, _) = context.memory_info().map_err(|error| context_failure(context, failed, error))?; + if free < required { + return Err(Error::InputAllocation); + } + Ok(()) +} +fn open_workspace<'ctx>(context: &'ctx Context<'ctx>, failed: &Cell) -> Result> { + let workspace = context.qsa_selected_kv_workspace().map_err(|error| context_failure(context, failed, error))?; + if workspace.allocated_bytes() != WORKSPACE_BYTES { + if workspace.close().is_err() { + failed.set(true); + } + return Err(Error::InvalidDimension); + } + Ok(workspace) +} impl<'ctx> QsaSelectedCache<'ctx> { pub(in crate::qwen_forward) fn new( binding: BindingIdentity, context: &'ctx Context<'ctx>, failed: Rc>, ) -> Result { - if failed.get() || context.is_poisoned() { - return Err(Error::CudaExecution); - } - let required = WORKSPACE_BYTES.checked_add(device_peak()).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(required).is_none_or(|bytes| bytes > context.budget_bytes()) { - return Err(Error::InputAllocation); - } - let (free, _) = context.memory_info().map_err(|error| { - if context.is_poisoned() { - failed.set(true); - } - driver_error(error) - })?; - if free < required { - return Err(Error::InputAllocation); - } + admit_workspace(context, &failed)?; let mut layers = reserve(12)?; for _ in 0..12 { layers.push(LayerDirectory::empty()?); } let layers = layers.try_into().map_err(|_| Error::InvalidDimension)?; - let workspace = context.qsa_selected_kv_workspace().map_err(|error| { - if context.is_poisoned() { - failed.set(true); - } - driver_error(error) - })?; - if workspace.allocated_bytes() != WORKSPACE_BYTES { - if workspace.close().is_err() { - failed.set(true); - } - return Err(Error::InvalidDimension); - } + let workspace = open_workspace(context, &failed)?; Ok(Self { binding, context, failed, layers, workspace: Some(workspace) }) } - pub(in crate::qwen_forward) fn attend( - &mut self, + /// The pre-device guards of `attend`: the cache is healthy, and the prepared candidate belongs to this + /// binding, context and a causal layer. Returns the layer and its directory slot. + fn admit_attend( + &self, binding: &BindingIdentity, context: &Context<'_>, prepared: &QsaPrepared, - query: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + ) -> Result<(u32, usize)> { if self.failed.get() || self.context.is_poisoned() || self.workspace.as_ref().is_none_or(|workspace| workspace.is_failed()) @@ -196,8 +227,18 @@ impl<'ctx> QsaSelectedCache<'ctx> { { return Err(Error::IdentityMismatch); } - let slot = (layer / 4) as usize; - let plan = plan(&self.layers[slot], candidate, &prepared.ids)?; + Ok((layer, (layer / 4) as usize)) + } + pub(in crate::qwen_forward) fn attend( + &mut self, + binding: &BindingIdentity, + context: &Context<'_>, + prepared: &QsaPrepared, + query: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + 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)?; let operation = (|| { let products = diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs index 472b2957..46fb0c42 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs @@ -16,6 +16,25 @@ const RESERVE: usize = 128 * 1024 * 1024; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) const ROUTER_BYTES: usize = 14416; +/// The scratch must fit the context budget and the free device memory; a failed memory query marks it failed. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn admit_router(context: &Context<'_>, failed: &Cell) -> Result<()> { + if failed.get() || context.is_poisoned() { + return Err(Error::CudaExecution); + } + let needed = ROUTER_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) { + return Err(Error::InputAllocation); + } + let (free, _) = context.memory_info().map_err(|error| { + failed.set(true); + map_driver_error(error) + })?; + if free < needed { + return Err(Error::InputAllocation); + } + Ok(()) +} // Numeric storage has no model certificate. Only the outer authenticated loan // can expose its products to the model. The test child can compare real buffers. struct RouterBuffers<'ctx> { @@ -26,20 +45,7 @@ struct RouterBuffers<'ctx> { impl<'ctx> RouterBuffers<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn new(context: &'ctx Context<'ctx>, failed: Rc>) -> Result { - if failed.get() || context.is_poisoned() { - return Err(Error::CudaExecution); - } - let needed = ROUTER_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) { - return Err(Error::InputAllocation); - } - let (free, _) = context.memory_info().map_err(|error| { - failed.set(true); - map_driver_error(error) - })?; - if free < needed { - return Err(Error::InputAllocation); - } + admit_router(context, &failed)?; let mut result = Self { context, slots: std::array::from_fn(|_| None), failed }; for (index, bytes) in EXTENTS.into_iter().enumerate() { match context.allocate(bytes) { @@ -65,6 +71,26 @@ impl<'ctx> RouterBuffers<'ctx> { } Ok(()) } + /// A failed CUDA execution or a poisoned context marks the scratch failed; other refusals leave it healthy. + fn note_outcome(&self, operation: &Result) { + if operation.as_ref().err() == Some(&Error::CudaExecution) || self.context.is_poisoned() { + self.failed.set(true); + } + } + fn run_project(&mut self, matrix: &DeviceBuffer<'_>, input_bytes: &[u8; 10240]) -> Result<[f32; 512]> { + let [input, output, _, _, _] = &mut self.slots; + let input = input.as_mut().ok_or(Error::IdentityMismatch)?; + let output = output.as_mut().ok_or(Error::IdentityMismatch)?; + input.copy_from(input_bytes).map_err(map_driver_error)?; + self.context + .bf16_f32(matrix, input, output, Bf16ProjectionShape { rows: 512, columns: 2560 }) + .map_err(map_driver_error)?; + let mut bytes = [0u8; 2048]; + output.copy_to(&mut bytes).map_err(map_driver_error)?; + Ok(std::array::from_fn(|i| { + f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("fixed router output")) + })) + } fn project(&mut self, matrix: &DeviceBuffer<'_>, activation: &[f32]) -> Result<[f32; 512]> { self.check()?; validate_activation(activation)?; @@ -75,29 +101,34 @@ impl<'ctx> RouterBuffers<'ctx> { for (bytes, value) in input_bytes.as_chunks_mut::<4>().0.iter_mut().zip(activation) { *bytes = value.to_bits().to_le_bytes(); } - let operation = (|| -> Result<[f32; 512]> { - let [input, output, _, _, _] = &mut self.slots; - let input = input.as_mut().ok_or(Error::IdentityMismatch)?; - let output = output.as_mut().ok_or(Error::IdentityMismatch)?; - input.copy_from(&input_bytes).map_err(map_driver_error)?; - self.context - .bf16_f32(matrix, input, output, Bf16ProjectionShape { rows: 512, columns: 2560 }) - .map_err(map_driver_error)?; - let mut bytes = [0u8; 2048]; - output.copy_to(&mut bytes).map_err(map_driver_error)?; - Ok(std::array::from_fn(|i| { - f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("fixed router output")) - })) - })(); - if operation.as_ref().err() == Some(&Error::CudaExecution) || self.context.is_poisoned() { - self.failed.set(true); - } + let operation = self.run_project(matrix, &input_bytes); + self.note_outcome(&operation); let values = operation?; // Numerical refusal leaves reusable buffers healthy; the next call fully // overwrites every producer role before it reads that role. validate_logits(&values)?; Ok(values) } + fn run_route(&mut self, logits_bytes: &[u8; 2048]) -> Result<([i32; 10], [f32; 10])> { + let [_, _, input, ids, weights] = &mut self.slots; + let input = input.as_mut().ok_or(Error::IdentityMismatch)?; + let ids = ids.as_mut().ok_or(Error::IdentityMismatch)?; + let weights = weights.as_mut().ok_or(Error::IdentityMismatch)?; + input.copy_from(logits_bytes).map_err(map_driver_error)?; + self.context.qwen_route_top10(input, ids, weights).map_err(map_driver_error)?; + let mut ids_bytes = [0u8; 40]; + let mut weights_bytes = [0u8; 40]; + ids.copy_to(&mut ids_bytes).map_err(map_driver_error)?; + weights.copy_to(&mut weights_bytes).map_err(map_driver_error)?; + Ok(( + std::array::from_fn(|i| { + i32::from_ne_bytes(ids_bytes[i * 4..i * 4 + 4].try_into().expect("fixed ID extent")) + }), + std::array::from_fn(|i| { + f32::from_ne_bytes(weights_bytes[i * 4..i * 4 + 4].try_into().expect("fixed weight extent")) + }), + )) + } fn route(&mut self, values: &[f32; 512]) -> Result<([i32; 10], [f32; 10])> { self.check()?; validate_logits(values)?; @@ -105,29 +136,8 @@ impl<'ctx> RouterBuffers<'ctx> { for (bytes, value) in logits_bytes.as_chunks_mut::<4>().0.iter_mut().zip(values) { *bytes = value.to_ne_bytes(); } - let operation = (|| -> Result<([i32; 10], [f32; 10])> { - let [_, _, input, ids, weights] = &mut self.slots; - let input = input.as_mut().ok_or(Error::IdentityMismatch)?; - let ids = ids.as_mut().ok_or(Error::IdentityMismatch)?; - let weights = weights.as_mut().ok_or(Error::IdentityMismatch)?; - input.copy_from(&logits_bytes).map_err(map_driver_error)?; - self.context.qwen_route_top10(input, ids, weights).map_err(map_driver_error)?; - let mut ids_bytes = [0u8; 40]; - let mut weights_bytes = [0u8; 40]; - ids.copy_to(&mut ids_bytes).map_err(map_driver_error)?; - weights.copy_to(&mut weights_bytes).map_err(map_driver_error)?; - Ok(( - std::array::from_fn(|i| { - i32::from_ne_bytes(ids_bytes[i * 4..i * 4 + 4].try_into().expect("fixed ID extent")) - }), - std::array::from_fn(|i| { - f32::from_ne_bytes(weights_bytes[i * 4..i * 4 + 4].try_into().expect("fixed weight extent")) - }), - )) - })(); - if operation.as_ref().err() == Some(&Error::CudaExecution) || self.context.is_poisoned() { - self.failed.set(true); - } + let operation = self.run_route(&logits_bytes); + self.note_outcome(&operation); operation } fn drain(&mut self) -> Result<()> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs index 3fe04666..dcecb043 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs @@ -20,50 +20,39 @@ struct Report { ties: usize, } -#[test] -#[ignore] -fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { - if std::env::var(ENABLE).as_deref() != Ok("yes") { - println!("SKIP: {ENABLE}=yes required"); - return; +/// What closing a set of contexts observed: whether each synchronized, how many bytes it still held, whether it closed. +struct Teardown { + synchronized: [bool; N], + allocated: [usize; N], + closed: [bool; N], +} +impl Teardown { + /// Synchronize every context, read every allocation, then close every context, in that order. + fn of(contexts: [Context<'_>; N]) -> Self { + let synchronized = contexts.each_ref().map(|context| context.synchronize().is_ok()); + let allocated = contexts.each_ref().map(|context| context.allocated_bytes()); + let closed = contexts.map(|context| context.close().is_ok()); + Self { synchronized, allocated, closed } } - let driver = Driver::load().expect("actual CUDA driver"); - let device = driver.device(0).expect("actual CUDA device"); - let context = device.create_context(BUDGET).expect("main numeric context"); - let foreign_context = device.create_context(16 * 1024 * 1024).expect("foreign numeric context"); - let small_context = device.create_context(RESERVE + ROUTER_BYTES - 1).expect("budget refusal context"); - let mut report = Report::default(); - let small_before = small_context.allocated_bytes(); - let small = RouterBuffers::new(&small_context, Rc::new(Cell::new(false))); + fn healthy(&self) -> bool { + self.synchronized.iter().chain(&self.closed).all(|&ok| ok) + } +} + +/// A context one byte below the scratch need refuses with an input allocation error and keeps nothing. +fn refuse_small_budget(context: Context<'_>, report: &mut Report) -> Teardown<1> { + let before = context.allocated_bytes(); + let small = RouterBuffers::new(&context, Rc::new(Cell::new(false))); report.guard(matches!(small, Err(Error::InputAllocation))); drop(small); - report.guard(small_context.allocated_bytes() == small_before); - let small_sync = small_context.synchronize(); - let small_allocated = small_context.allocated_bytes(); - let small_close = small_context.close(); - let operation = catch_unwind(AssertUnwindSafe(|| numeric(&context, &foreign_context, &mut report))); - let main_sync = context.synchronize(); - let foreign_sync = foreign_context.synchronize(); - let main_allocated = context.allocated_bytes(); - let foreign_allocated = foreign_context.allocated_bytes(); - let main_close = context.close(); - let foreign_close = foreign_context.close(); - match operation { - Err(panic) => resume_unwind(panic), - Ok(Err(error)) => panic!("original-first router operation refused: {error:?}"), - Ok(Ok(())) => {} - } - assert!( - small_sync.is_ok() - && small_close.is_ok() - && main_sync.is_ok() - && foreign_sync.is_ok() - && main_close.is_ok() - && foreign_close.is_ok() - ); - assert_eq!((small_allocated, main_allocated, foreign_allocated), (0, 0, 0)); + report.guard(context.allocated_bytes() == before); + Teardown::of([context]) +} + +fn assert_report(report: &Report) { println!( - "ROUTER_SCRATCH_COMPLETE cases={} logits_words={} ids={} weights={} differences={} guards={} failed_guards={} resets={} ties={} allocated=0 component_only=true", + "ROUTER_SCRATCH_COMPLETE cases={} logits_words={} ids={} weights={} differences={} guards={} \ + failed_guards={} resets={} ties={} allocated=0 component_only=true", report.cases, report.logits_words, report.ids, @@ -81,6 +70,32 @@ fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { assert_eq!(report.ties, 1); } +#[test] +#[ignore] +fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { + if std::env::var(ENABLE).as_deref() != Ok("yes") { + println!("SKIP: {ENABLE}=yes required"); + return; + } + let driver = Driver::load().expect("actual CUDA driver"); + let device = driver.device(0).expect("actual CUDA device"); + let context = device.create_context(BUDGET).expect("main numeric context"); + let foreign_context = device.create_context(16 * 1024 * 1024).expect("foreign numeric context"); + let small_context = device.create_context(RESERVE + ROUTER_BYTES - 1).expect("budget refusal context"); + let mut report = Report::default(); + let small = refuse_small_budget(small_context, &mut report); + let operation = catch_unwind(AssertUnwindSafe(|| numeric(&context, &foreign_context, &mut report))); + let both = Teardown::of([context, foreign_context]); + match operation { + Err(panic) => resume_unwind(panic), + Ok(Err(error)) => panic!("original-first router operation refused: {error:?}"), + Ok(Ok(())) => {} + } + assert!(small.healthy() && both.healthy()); + assert_eq!((small.allocated[0], both.allocated[0], both.allocated[1]), (0, 0, 0)); + assert_report(&report); +} + #[path = "router_scratch_gpu/impl_report.rs"] mod impl_report; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs index 3d1a6258..1ea54f4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs @@ -18,131 +18,196 @@ pub(super) fn valid_reset( Ok(()) } -pub(super) fn numeric<'ctx>( +type Product = ([f32; 512], [i32; 10], [f32; 10]); + +/// The context, workspace and report every proof step shares. +struct Env<'a, 'ctx> { context: &'ctx Context<'ctx>, - foreign_context: &Context<'_>, - report: &mut Report, -) -> Result<()> { - let mut buffers: [Option>; 2] = std::array::from_fn(|_| None); - let mut foreign = None; - let mut workspace = None; - let operation: Result<()> = (|| { - buffers[0] = Some(context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); - buffers[1] = Some(context.allocate(MATRIX_BYTES - 2).map_err(map_driver_error)?); - foreign = Some(foreign_context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); - let baseline = matrix_bytes(); - let [matrix, short] = &mut buffers; - let matrix = matrix.as_mut().ok_or(Error::IdentityMismatch)?; - let short = short.as_ref().ok_or(Error::IdentityMismatch)?; - matrix.copy_from(&baseline).map_err(map_driver_error)?; - foreign.as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&baseline).map_err(map_driver_error)?; - let before = context.allocated_bytes(); - workspace = Some(RouterBuffers::new(context, Rc::new(Cell::new(false)))?); - report.guard(context.allocated_bytes() == before + ROUTER_BYTES); - let workspace = workspace.as_mut().ok_or(Error::IdentityMismatch)?; - for (slot, extent) in workspace.slots.iter().zip(EXTENTS) { - report.guard(slot.as_ref().is_some_and(|b| b.len() == extent)); + workspace: &'a mut RouterBuffers<'ctx>, + report: &'a mut Report, +} +impl Env<'_, '_> { + fn reset(&mut self, matrix: &DeviceBuffer<'_>, values: &[f32]) -> Result<()> { + valid_reset(self.workspace, matrix, values, self.context, self.report) + } + /// The candidate refuses `values` like the original and leaves every retained slot byte untouched. + fn project_refused(&mut self, matrix: &DeviceBuffer<'_>, values: &[f32], expect: Error) -> Result<()> { + let old = original_project(self.context, matrix, values).err(); + let before = snapshot(self.workspace)?; + let actual = self.workspace.project(matrix, values).err(); + self.report.guard(old == Some(expect) && actual == old && snapshot(self.workspace)? == before); + Ok(()) + } + fn route_refused(&mut self, logits: &[f32; 512], expect: Error) -> Result<()> { + let old = original_route(self.context, logits).err(); + let before = snapshot(self.workspace)?; + let actual = self.workspace.route(logits).err(); + self.report.guard(old == Some(expect) && actual == old && snapshot(self.workspace)? == before); + Ok(()) + } + /// The same refusal, but the driver may refuse after the scratch input upload (no prewrite provenance). + fn project_refused_late(&mut self, matrix: &DeviceBuffer<'_>, values: &[f32], expect: Error) { + let old = original_project(self.context, matrix, values).err(); + let actual = self.workspace.project(matrix, values).err(); + self.report.guard(old == Some(expect) && actual == old); + healthy(self.workspace, self.context, self.report); + } +} + +/// The device buffers a proof run holds; released in the order workspace, matrices, foreign matrix. +struct Held<'ctx, 'f> { + buffers: [Option>; 2], + foreign: Option>, + workspace: Option>, +} +impl Held<'_, '_> { + fn release(&mut self) -> Result<()> { + let mut primary_cleanup = None; + if let Some(owner) = self.workspace.take() { + if let Err(error) = owner.close() { + primary_cleanup = Some(error); + } } + if let Err(error) = close_all(&mut self.buffers) { + primary_cleanup.get_or_insert(error); + } + if let Some(buffer) = self.foreign.take() { + if let Err(error) = buffer.release() { + primary_cleanup.get_or_insert(map_driver_error(error)); + } + } + primary_cleanup.map_or(Ok(()), Err) + } +} + +struct Proof<'a, 'ctx, 'f> { + env: Env<'a, 'ctx>, + matrix: &'a mut DeviceBuffer<'ctx>, + short: &'a DeviceBuffer<'ctx>, + foreign: &'a DeviceBuffer<'f>, + baseline: Vec, +} +fn open_proof<'a, 'ctx, 'f>( + (context, foreign_context): (&'ctx Context<'ctx>, &'f Context<'f>), + report: &'a mut Report, + held: &'a mut Held<'ctx, 'f>, +) -> Result> { + held.buffers[0] = Some(context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); + held.buffers[1] = Some(context.allocate(MATRIX_BYTES - 2).map_err(map_driver_error)?); + held.foreign = Some(foreign_context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); + let baseline = matrix_bytes(); + let [matrix, short] = &mut held.buffers; + let matrix = matrix.as_mut().ok_or(Error::IdentityMismatch)?; + let short = short.as_ref().ok_or(Error::IdentityMismatch)?; + matrix.copy_from(&baseline).map_err(map_driver_error)?; + held.foreign.as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&baseline).map_err(map_driver_error)?; + let before = context.allocated_bytes(); + held.workspace = Some(RouterBuffers::new(context, Rc::new(Cell::new(false)))?); + report.guard(context.allocated_bytes() == before + ROUTER_BYTES); + let workspace = held.workspace.as_mut().ok_or(Error::IdentityMismatch)?; + for (slot, extent) in workspace.slots.iter().zip(EXTENTS) { + report.guard(slot.as_ref().is_some_and(|b| b.len() == extent)); + } + let foreign = held.foreign.as_ref().ok_or(Error::IdentityMismatch)?; + Ok(Proof { env: Env { context, workspace, report }, matrix, short, foreign, baseline }) +} +impl Proof<'_, '_, '_> { + fn run(&mut self) -> Result<()> { let inputs: [Vec; 4] = std::array::from_fn(activation); + let (expected, charged) = self.arms(&inputs)?; + self.changed_matrix(&inputs[0])?; + self.nonfinite(&inputs[0], &expected[0].0)?; + self.dimension_refusals(&inputs[0])?; + self.late_poison(&inputs[0])?; + self.foreign_and_budget(&inputs[0], charged) + } + /// The original products of all four inputs, then the candidate over the five-arm repeat/reset order. + fn arms(&mut self, inputs: &[Vec; 4]) -> Result<(Vec, usize)> { let mut expected = Vec::new(); // All four independent original producer products exist before candidate work. - for values in &inputs { - expected.push(original(context, matrix, values)?); + for values in inputs { + expected.push(original(self.env.context, self.matrix, values)?); } - report.guard(expected[2].1 == std::array::from_fn(|i| i as i32)); - report.ties += 1; - let charged = context.allocated_bytes(); + self.env.report.guard(expected[2].1 == std::array::from_fn(|i| i as i32)); + self.env.report.ties += 1; + let charged = self.env.context.allocated_bytes(); for arm in [0, 1, 2, 3, 0] { - let actual = candidate(workspace, matrix, &inputs[arm])?; - report.compare(&expected[arm], &actual); - report.guard(context.allocated_bytes() == charged); + let actual = candidate(self.env.workspace, self.matrix, &inputs[arm])?; + self.env.report.compare(&expected[arm], &actual); + self.env.report.guard(self.env.context.allocated_bytes() == charged); } - // Change the last matrix row, independently capture it, then restore and repeat. - let mut changed = baseline.clone(); + Ok((expected, charged)) + } + /// Change the last matrix row, independently capture it, then restore and repeat. + fn changed_matrix(&mut self, input: &[f32]) -> Result<()> { + let mut changed = self.baseline.clone(); for half in changed[MATRIX_BYTES - 5120..].as_chunks_mut::<2>().0.iter_mut() { *half = 0x3f80u16.to_le_bytes(); } - matrix.copy_from(&changed).map_err(map_driver_error)?; + self.matrix.copy_from(&changed).map_err(map_driver_error)?; let changed_input = vec![1.0; 2560]; - let changed_expected = original(context, matrix, &changed_input)?; - let changed_actual = candidate(workspace, matrix, &changed_input)?; - report.compare(&changed_expected, &changed_actual); - report.guard(changed_expected.1[0] == 511); - matrix.copy_from(&baseline).map_err(map_driver_error)?; - valid_reset(workspace, matrix, &inputs[0], context, report)?; - - // Prewrite host/whole-extent refusal preserves every retained slot byte. + let changed_expected = original(self.env.context, self.matrix, &changed_input)?; + let changed_actual = candidate(self.env.workspace, self.matrix, &changed_input)?; + self.env.report.compare(&changed_expected, &changed_actual); + self.env.report.guard(changed_expected.1[0] == 511); + self.matrix.copy_from(&self.baseline).map_err(map_driver_error)?; + self.env.reset(self.matrix, input) + } + /// Prewrite host/whole-extent refusal preserves every retained slot byte. + fn nonfinite(&mut self, input: &[f32], logits: &[f32; 512]) -> Result<()> { for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let mut values = inputs[0].clone(); + let mut values = input.to_vec(); values[2559] = bad; - let old = original_project(context, matrix, &values).err(); - let before = snapshot(workspace)?; - let actual = workspace.project(matrix, &values).err(); - report.guard(old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before); - valid_reset(workspace, matrix, &inputs[0], context, report)?; - let mut logits = expected[0].0; + self.env.project_refused(self.matrix, &values, Error::NonFinite)?; + self.env.reset(self.matrix, input)?; + let mut logits = *logits; logits[511] = bad; - let old = original_route(context, &logits).err(); - let before = snapshot(workspace)?; - let actual = workspace.route(&logits).err(); - report.guard(old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before); - valid_reset(workspace, matrix, &inputs[0], context, report)?; + self.env.route_refused(&logits, Error::NonFinite)?; + self.env.reset(self.matrix, input)?; } - for values in [&inputs[0][..2559], &inputs[0][..0]] { - let old = original_project(context, matrix, values).err(); - let before = snapshot(workspace)?; - let actual = workspace.project(matrix, values).err(); - report.guard(old == Some(Error::InvalidDimension) && actual == old && snapshot(workspace)? == before); + Ok(()) + } + fn dimension_refusals(&mut self, input: &[f32]) -> Result<()> { + for values in [&input[..2559], &input[..0]] { + self.env.project_refused(self.matrix, values, Error::InvalidDimension)?; } - let old = original_project(context, short, &inputs[0]).err(); - let before = snapshot(workspace)?; - let actual = workspace.project(short, &inputs[0]).err(); - report.guard(old == Some(Error::InvalidDimension) && actual == old && snapshot(workspace)? == before); - - // Actual late projection NaN/Inf is detected by full512 readback, then reset. + self.env.project_refused(self.short, input, Error::InvalidDimension) + } + /// Actual late projection NaN/Inf is detected by full512 readback, then reset. + fn late_poison(&mut self, input: &[f32]) -> Result<()> { for half in [0x7fc1u16, 0x7f80u16, 0xff80u16] { - let mut poisoned = baseline.clone(); + let mut poisoned = self.baseline.clone(); poisoned[MATRIX_BYTES - 2..].copy_from_slice(&half.to_le_bytes()); - matrix.copy_from(&poisoned).map_err(map_driver_error)?; - let mut values = inputs[0].clone(); + self.matrix.copy_from(&poisoned).map_err(map_driver_error)?; + let mut values = input.to_vec(); values[2559] = 1.0; - let old = original_project(context, matrix, &values).err(); - let actual = workspace.project(matrix, &values).err(); - report.guard(old == Some(Error::NonFinite) && actual == old); - healthy(workspace, context, report); - matrix.copy_from(&baseline).map_err(map_driver_error)?; - valid_reset(workspace, matrix, &inputs[0], context, report)?; + self.env.project_refused_late(self.matrix, &values, Error::NonFinite); + self.matrix.copy_from(&self.baseline).map_err(map_driver_error)?; + self.env.reset(self.matrix, input)?; } - // Genuine foreign matrix: driver's refusal may follow scratch input upload. + Ok(()) + } + fn foreign_and_budget(&mut self, input: &[f32], charged: usize) -> Result<()> { + // Genuine foreign matrix: driver refusal may follow scratch input upload. // Do not assert nonexistent prewrite provenance or fabricate a model owner. - let foreign_matrix = foreign.as_ref().ok_or(Error::IdentityMismatch)?; - let old = original_project(context, foreign_matrix, &inputs[0]).err(); - let actual = workspace.project(foreign_matrix, &inputs[0]).err(); - report.guard(old == Some(Error::IdentityMismatch) && actual == old); - healthy(workspace, context, report); - valid_reset(workspace, matrix, &inputs[0], context, report)?; + self.env.project_refused_late(self.foreign, input, Error::IdentityMismatch); + self.env.reset(self.matrix, input)?; + let (context, report) = (self.env.context, &mut *self.env.report); report.guard(context.allocated_bytes() == charged); let before = context.allocated_bytes(); report.guard(RouterBuffers::new(context, Rc::new(Cell::new(true))).is_err()); report.guard(context.allocated_bytes() == before); Ok(()) - })(); - let mut primary_cleanup = None; - if let Some(owner) = workspace.take() { - if let Err(error) = owner.close() { - primary_cleanup = Some(error); - } } - if let Err(error) = close_all(&mut buffers) { - primary_cleanup.get_or_insert(error); - } - if let Some(buffer) = foreign.take() { - if let Err(error) = buffer.release() { - primary_cleanup.get_or_insert(map_driver_error(error)); - } - } - drop(workspace); - drop(foreign); - drop(buffers); - finish(operation, primary_cleanup.map_or(Ok(()), Err)) +} + +pub(super) fn numeric<'ctx>( + context: &'ctx Context<'ctx>, + foreign_context: &Context<'_>, + report: &mut Report, +) -> Result<()> { + let mut held = Held { buffers: std::array::from_fn(|_| None), foreign: None, workspace: None }; + let operation = open_proof((context, foreign_context), report, &mut held).and_then(|mut proof| proof.run()); + let cleanup = held.release(); + finish(operation, cleanup) }