From 7c6cc64751caed11fd454422f543699c58de36dd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 10 Oct 2026 08:54:53 +0200 Subject: [PATCH] Retain GDN and MTP CUDA products through inference chains --- crates/leleka-runtime/src/qwen_forward/gdn.rs | 160 +++++++ .../src/qwen_forward/gdn_chain.rs | 410 ++++++++++++++++++ .../src/qwen_forward/gdn_chain_reuse_gpu.rs | 340 +++++++++++++++ .../src/qwen_forward/gdn_state_mirror.rs | 122 +++++- crates/leleka-runtime/src/qwen_forward/mtp.rs | 75 +++- .../src/qwen_forward/mtp_attention.rs | 244 ++++++++++- .../qwen_forward/mtp_attention_reuse_gpu.rs | 321 ++++++++++++++ 7 files changed, 1658 insertions(+), 14 deletions(-) create mode 100644 crates/leleka-runtime/src/qwen_forward/gdn_chain.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/gdn_chain_reuse_gpu.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/mtp_attention_reuse_gpu.rs diff --git a/crates/leleka-runtime/src/qwen_forward/gdn.rs b/crates/leleka-runtime/src/qwen_forward/gdn.rs index 3182220e..cfc8dd8c 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn.rs @@ -23,6 +23,8 @@ pub(super) use mirror::{ALL_MIRROR_BYTES, GdnStateMirror}; #[path = "gdn_input_scratch.rs"] mod input_scratch; pub(super) use input_scratch::{GdnInputLease, GdnInputScratch}; +#[path = "gdn_chain.rs"] +mod chain; const WIDTH: usize = 128; const KEY_HEADS: usize = 16; const VALUE_HEADS: usize = 48; @@ -88,6 +90,9 @@ impl GdnStage { validate_values(input.mixed(), 2560)?; let context = txn.cuda_context()?; preflight_budget(context.budget_bytes(), context.allocated_bytes())?; + if let Some(cache) = cache { + return step_cached(binding, layer, input, prior, context, cache); + } let resident = cache.map(|c| c.gdn(binding, layer.get())).transpose()?; let mut mirror = cache .map(|c| c.gdn_mirror(binding, layer.get(), context)) @@ -232,6 +237,161 @@ impl GdnStage { operation } } +fn step_cached<'ctx>( + binding: &ModelBinding, + layer: LayerId, + input: &ResidualReady, + prior: &GdnPrior, + current_context: &Context<'_>, + cache: &DenseWeightCache<'ctx>, +) -> Result { + use chain::Role; + let context = cache.retained_context(binding, current_context)?; + let failed = cache.transport_failure_flag(binding, context)?; + let resident = cache.gdn(binding, layer.get())?; + let weights = resident.weights.clone(); + let aux = cache.gdn_aux(resident)?; + let mut mirror = cache.gdn_mirror(binding, layer.get(), context)?; + let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?; + let mut chain = chain::Chain::new( + context, + binding.identity(), + input.identity(), + failed.clone(), + )?; + chain.validate(context, &binding.identity(), input.identity())?; + let mut mirror_next = None; + let operation = (|| -> Result { + let qkv = project_chain_input( + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Qkv, + &input_lease, + input.mixed(), + cache, + )?; + let history = chain.upload(Role::History, prior.history())?; + let (next_history, h) = chain.convolve(&history, &qkv, aux[0])?; + let qk = chain.normalize_qk(&h, weights.epsilon())?; + let alpha = project_chain_input( + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Alpha, + &input_lease, + input.mixed(), + cache, + )?; + let beta_raw = project_chain_input( + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Beta, + &input_lease, + input.mixed(), + cache, + )?; + let (gate, beta) = chain.gates(&alpha, &beta_raw, aux[1], aux[2])?; + let history = next_history.into_values(); + let h = h.into_values(); + let qk = qk.into_values(); + let gate = gate.into_values(); + let beta = beta.into_values(); + // Recurrence's unchanged128MiB preflight sees no additional retained + // activation allocations. Host state/history remain the canonical proof. + chain.drain()?; + let (readout, next) = mirror.compute_retained( + prior, + input.identity(), + chain.scope_key(), + [&qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta], + )?; + mirror_next = Some(next); + let readout = chain.import_readout(readout, prior)?; + let z = project_chain_input( + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Z, + &input_lease, + input.mixed(), + cache, + )?; + let normalized = chain.out_norm(&readout, &z, aux[3], weights.epsilon())?; + let (matrix, kind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?; + let output = chain.project_out(matrix, kind, &normalized)?.into_values(); + validate_values(&output, 2560)?; + Ok((history, output)) + })(); + if matches!(operation, Err(Error::CudaExecution)) { + failed.set(true); + } + let cleanup = chain.finish(); + drop(input_lease); + let result = operation.and_then(|values| cleanup.map(|()| values)); + let (history, output) = match result { + Ok(values) => values, + Err(primary) => { + if let Some(next) = mirror_next { + let _ = mirror.discard(next); + } + return Err(primary); + } + }; + let pending = mirror.publish( + mirror_next.take().ok_or(Error::IdentityMismatch)?, + input.identity(), + history, + )?; + Ok(GdnReady { + identity: input.identity(), + binding: binding.identity(), + output, + pending: Some(pending), + }) +} + +#[allow(clippy::too_many_arguments)] // Explicit closed provider and current input-lease checks. +fn project_chain_input<'ctx>( + chain: &mut chain::Chain<'ctx>, + context: &Context<'_>, + binding: &ModelBinding, + weights: &GdnWeights, + role: GdnMatrixRole, + source: &GdnInputLease<'_, '_, 'ctx>, + activation: &[f32], + cache: &DenseWeightCache<'ctx>, +) -> Result { + let output_role = match role { + GdnMatrixRole::Qkv => chain::Role::Qkv, + GdnMatrixRole::Alpha => chain::Role::Alpha, + GdnMatrixRole::Beta => chain::Role::BetaRaw, + GdnMatrixRole::Z => chain::Role::Z, + GdnMatrixRole::Out => return Err(Error::IdentityMismatch), + }; + let (columns, rows) = weights.shape(role); + validate_values(activation, columns)?; + let activation = source.buffer( + &binding.identity(), + context, + weights.layer(), + role, + activation, + )?; + let resident = cache.gdn(binding, weights.layer())?; + if !std::ptr::eq(resident.weights.as_ref(), weights) { + return Err(Error::IdentityMismatch); + } + let (matrix, kind) = cache.gdn_matrix(resident, role)?; + let product = chain.project(matrix, kind, activation, output_role)?; + validate_values(product.values(), rows)?; + Ok(product) +} fn preflight_budget(budget: usize, allocated: usize) -> Result<()> { if allocated .checked_add(DEVICE_PEAK) diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain.rs new file mode 100644 index 00000000..21ff7b27 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain.rs @@ -0,0 +1,410 @@ +//! Step-local actual CUDA products; canonical finite host readbacks stay intact. +use super::{ + BindingIdentity, CHANNELS, Context, DeviceBuffer, Error, GdnMatrixKind, HISTORY_ELEMENTS, + Result, TokenLayer, VALUES, allocate, dispatch_projection, download, driver_error, + validate_values, +}; +use std::{cell::Cell, rc::Rc}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum Role { + Input, + Qkv, + History, + Conv, + NextHistory, + Raw, + H, + Qk, + Alpha, + BetaRaw, + Dt, + A, + Gate, + Beta, + Readout, + Z, + Gamma, + Normalized, + Out, +} +impl Role { + fn count(self) -> usize { + match self { + Self::Input | Self::Out => 2560, + Self::Qkv | Self::Raw | Self::H | Self::Qk => CHANNELS, + Self::History | Self::NextHistory => HISTORY_ELEMENTS, + Self::Conv => 4 * CHANNELS, + Self::Alpha | Self::BetaRaw | Self::Dt | Self::A | Self::Gate | Self::Beta => 48, + Self::Readout | Self::Z | Self::Normalized => VALUES, + Self::Gamma => 128, + } + } +} +pub(super) struct Product { + slot: usize, + role: Role, + epoch: Rc<()>, + values: Box<[f32]>, +} +impl Product { + pub(super) fn values(&self) -> &[f32] { + &self.values + } + pub(super) fn into_values(self) -> Box<[f32]> { + self.values + } +} +pub(super) struct Chain<'ctx> { + context: &'ctx Context<'ctx>, + binding: BindingIdentity, + identity: TokenLayer, + epoch: Rc<()>, + failed: Rc>, + buffers: Vec>>, +} +impl<'ctx> Chain<'ctx> { + pub(super) fn new( + context: &'ctx Context<'ctx>, + binding: BindingIdentity, + identity: TokenLayer, + failed: Rc>, + ) -> Result { + if failed.get() { + return Err(Error::CudaExecution); + } + if identity.layer().get() >= 48 || identity.layer().get() % 4 == 3 { + return Err(Error::InvalidLayer); + } + let mut buffers = Vec::new(); + buffers + .try_reserve_exact(32) + .map_err(|_| Error::InputAllocation)?; + Ok(Self { + context, + binding, + identity, + epoch: Rc::new(()), + failed, + buffers, + }) + } + pub(super) fn validate( + &self, + context: &Context<'_>, + binding: &BindingIdentity, + identity: TokenLayer, + ) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) + || !self.binding.matches(binding) + || self.identity != identity + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(super) fn scope_key(&self) -> Rc<()> { + self.epoch.clone() + } + fn check(&self) -> Result<()> { + if self.failed.get() { + Err(Error::CudaExecution) + } else { + Ok(()) + } + } + pub(super) fn buffer(&self, product: &Product, role: Role) -> Result<&DeviceBuffer<'ctx>> { + self.check()?; + if product.role != role || !Rc::ptr_eq(&self.epoch, &product.epoch) { + return Err(Error::IdentityMismatch); + } + validate_values(&product.values, role.count())?; + let buffer = self + .buffers + .get(product.slot) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if buffer.len() != role.count() * 4 { + return Err(Error::InvalidDimension); + } + Ok(buffer) + } + fn track(&mut self, role: Role, buffer: DeviceBuffer<'ctx>, values: Box<[f32]>) -> Product { + let slot = self.buffers.len(); + self.buffers.push(Some(buffer)); + Product { + slot, + role, + epoch: self.epoch.clone(), + values, + } + } + pub(super) fn upload(&mut self, role: Role, values: &[f32]) -> Result { + self.check()?; + if !matches!( + role, + Role::Input | Role::History | Role::Conv | Role::Dt | Role::A | Role::Gamma + ) { + return Err(Error::IdentityMismatch); + } + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + validate_values(values, role.count())?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(values.len() * 4) + .map_err(|_| Error::InputAllocation)?; + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } + let mut host = Vec::new(); + host.try_reserve_exact(values.len()) + .map_err(|_| Error::InputAllocation)?; + host.extend_from_slice(values); + let mut buffer = allocate(self.context, role.count())?; + if let Err(error) = buffer.copy_from(&bytes) { + let primary = driver_error(error); + self.note(primary); + self.free(buffer); + return Err(primary); + } + Ok(self.track(role, buffer, host.into_boxed_slice())) + } + fn note(&self, error: Error) { + if error == Error::CudaExecution { + self.failed.set(true); + } + } + fn free(&self, buffer: DeviceBuffer<'ctx>) -> Option { + match buffer.release() { + Ok(()) => None, + Err(error) => { + self.failed.set(true); + Some(driver_error(error)) + } + } + } + // Producers perform the kernel and all mandatory finite D2H themselves. + // Callers never provide a separately computed numeric proof for a buffer. + fn produce( + &mut self, + roles: [Role; N], + operation: impl FnOnce(&Self, &mut [DeviceBuffer<'ctx>]) -> Result<[Box<[f32]>; N]>, + ) -> Result<[Product; N]> { + self.check()?; + self.buffers + .try_reserve(N) + .map_err(|_| Error::InputAllocation)?; + let mut buffers = Vec::new(); + buffers + .try_reserve_exact(N) + .map_err(|_| Error::InputAllocation)?; + let mut products = Vec::new(); + products + .try_reserve_exact(N) + .map_err(|_| Error::InputAllocation)?; + let result = (|| { + for role in roles { + buffers.push(allocate(self.context, role.count())?); + } + operation(self, &mut buffers) + })(); + let values = match result { + Ok(values) => values, + Err(primary) => { + self.note(primary); + for buffer in buffers { + self.free(buffer); + } + return Err(primary); + } + }; + for ((buffer, values), role) in buffers.into_iter().zip(values).zip(roles) { + products.push(self.track(role, buffer, values)); + } + products.try_into().map_err(|_| Error::IdentityMismatch) + } + pub(super) fn project( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + source: &DeviceBuffer<'_>, + role: Role, + ) -> Result { + let columns = match role { + Role::Qkv | Role::Alpha | Role::BetaRaw | Role::Z => 2560, + _ => return Err(Error::IdentityMismatch), + }; + let [product] = self.produce([role], |chain, out| { + dispatch_projection( + chain.context, + matrix, + source, + &mut out[0], + kind, + columns, + role.count(), + ) + .map_err(driver_error)?; + Ok([download(&out[0], role.count())?]) + })?; + Ok(product) + } + pub(super) fn project_out( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + normalized: &Product, + ) -> Result { + let [product] = self.produce([Role::Out], |chain, out| { + dispatch_projection( + chain.context, + matrix, + chain.buffer(normalized, Role::Normalized)?, + &mut out[0], + kind, + VALUES, + 2560, + ) + .map_err(driver_error)?; + Ok([download(&out[0], 2560)?]) + })?; + Ok(product) + } + pub(super) fn convolve( + &mut self, + history: &Product, + qkv: &Product, + weights: &DeviceBuffer<'_>, + ) -> Result<(Product, Product)> { + let [next, _raw, h] = + self.produce([Role::NextHistory, Role::Raw, Role::H], |chain, out| { + let (next, rest) = out.split_at_mut(1); + let (raw, h) = rest.split_at_mut(1); + chain + .context + .gdn_conv_silu_f32( + chain.buffer(history, Role::History)?, + chain.buffer(qkv, Role::Qkv)?, + weights, + &mut next[0], + &mut raw[0], + &mut h[0], + ) + .map_err(driver_error)?; + let raw_values = download(&raw[0], CHANNELS)?; + let next_values = download(&next[0], HISTORY_ELEMENTS)?; + let h_values = download(&h[0], CHANNELS)?; + Ok([next_values, raw_values, h_values]) + })?; + Ok((next, h)) + } + pub(super) fn normalize_qk(&mut self, h: &Product, epsilon: f32) -> Result { + let [product] = self.produce([Role::Qk], |chain, out| { + // Fixed ABI writes only4096 words; preserve original initialized tail. + out[0] + .copy_from(&[0u8; CHANNELS * 4]) + .map_err(driver_error)?; + chain + .context + .gdn_qk_l2_f32(chain.buffer(h, Role::H)?, &mut out[0], epsilon) + .map_err(driver_error)?; + Ok([download(&out[0], CHANNELS)?]) + })?; + Ok(product) + } + pub(super) fn gates( + &mut self, + alpha: &Product, + beta: &Product, + dt: &DeviceBuffer<'_>, + a: &DeviceBuffer<'_>, + ) -> Result<(Product, Product)> { + let [sigmoid, gate] = self.produce([Role::Beta, Role::Gate], |chain, out| { + chain + .context + .gdn_beta_sigmoid_f32(chain.buffer(beta, Role::BetaRaw)?, &mut out[0]) + .map_err(driver_error)?; + // Read and validate sigmoid before invoking gate, matching legacy. + let sigmoid = download(&out[0], 48)?; + chain + .context + .gdn_gate_softplus_f32(chain.buffer(alpha, Role::Alpha)?, dt, a, &mut out[1]) + .map_err(driver_error)?; + Ok([sigmoid, download(&out[1], 48)?]) + })?; + Ok((gate, sigmoid)) + } + pub(super) fn import_readout( + &mut self, + readout: super::mirror::MirrorReadout<'ctx>, + prior: &super::GdnPrior, + ) -> Result { + self.check()?; + if !prior.mirror_admits(&self.binding, self.identity.layer().get()) { + return Err(Error::IdentityMismatch); + } + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + let (buffer, values) = readout.into_parts( + self.context, + &self.failed, + prior, + self.identity, + &self.epoch, + )?; + Ok(self.track(Role::Readout, buffer, values)) + } + pub(super) fn out_norm( + &mut self, + readout: &Product, + z: &Product, + gamma: &DeviceBuffer<'_>, + epsilon: f32, + ) -> Result { + let [product] = self.produce([Role::Normalized], |chain, out| { + chain + .context + .gdn_out_norm_f32( + chain.buffer(readout, Role::Readout)?, + chain.buffer(z, Role::Z)?, + gamma, + &mut out[0], + epsilon, + ) + .map_err(driver_error)?; + Ok([download(&out[0], VALUES)?]) + })?; + Ok(product) + } + pub(super) fn drain(&mut self) -> Result<()> { + // Epoch change makes all old capabilities invalid even when slots are reused. + self.epoch = Rc::new(()); + let mut error = None; + while let Some(buffer) = self.buffers.pop() { + if let Some(buffer) = buffer + && let Some(failure) = self.free(buffer) + { + error.get_or_insert(failure); + } + } + error.map_or(Ok(()), Err) + } + pub(super) fn finish(mut self) -> Result<()> { + self.drain() + } +} +impl Drop for Chain<'_> { + fn drop(&mut self) { + let _ = self.drain(); + } +} + +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +#[path = "gdn_chain_reuse_gpu.rs"] +mod gpu_tests; diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain_reuse_gpu.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain_reuse_gpu.rs new file mode 100644 index 00000000..4cb01ad3 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain_reuse_gpu.rs @@ -0,0 +1,340 @@ +//! Independent exact old-transfer versus retained GDN chain component proof. +#![cfg(all(target_os = "linux", target_arch = "x86_64"))] +use super::super::{ + GdnOwner, GdnPrior, GdnStateMirror, convolve, gates, normalize_qk, out_norm, recur, release, + upload, +}; +use super::*; +use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId}; +use leleka_cuda_driver::{Bf16ProjectionShape, Driver}; + +fn exact(a: &[f32], b: &[f32]) { + assert_eq!(a.len(), b.len()); + for (i, (a, b)) in a.iter().zip(b).enumerate() { + assert!(a.is_finite() && b.is_finite()); + assert_eq!(a.to_bits(), b.to_bits(), "word{i}"); + } +} +fn matrix(rows: usize, columns: usize, seed: usize) -> Vec { + (0..rows) + .flat_map(|row| { + (0..columns).flat_map(move |column| { + let v = (((row + 3 * column + seed) % 11) as f32 - 5.) / 4096.; + ((v.to_bits() >> 16) as u16).to_le_bytes() + }) + }) + .collect() +} +fn upload_bytes<'ctx>(ctx: &'ctx Context<'ctx>, bytes: &[u8]) -> DeviceBuffer<'ctx> { + let mut b = ctx.allocate(bytes.len()).unwrap(); + b.copy_from(bytes).unwrap(); + b +} +fn original_projection( + ctx: &Context<'_>, + weights: &DeviceBuffer<'_>, + input: &[f32], + rows: usize, +) -> Box<[f32]> { + let x = upload(ctx, input).unwrap(); + let mut y = allocate(ctx, rows).unwrap(); + ctx.bf16_f32( + weights, + &x, + &mut y, + Bf16ProjectionShape { + rows, + columns: input.len(), + }, + ) + .unwrap(); + let result = download(&y, rows).unwrap(); + release([x, y]).unwrap(); + result +} +fn pair_projection<'ctx>( + chain: &mut Chain<'ctx>, + source: &DeviceBuffer<'_>, + input: &[f32], + role: Role, + seed: usize, +) -> (Product, Box<[f32]>) { + let ctx = chain.context; + let bytes = matrix(role.count(), 2560, seed); + let weights = upload_bytes(ctx, &bytes); + let expected = original_projection(ctx, &weights, input, role.count()); + let product = chain + .project(&weights, GdnMatrixKind::Bf16, source, role) + .unwrap(); + exact(product.values(), &expected); + let mut after = vec![0; bytes.len()]; + weights.copy_to(&mut after).unwrap(); + assert_eq!(after, bytes); + weights.release().unwrap(); + (product, expected) +} +fn identity(layer: u64, position: u64) -> TokenLayer { + TokenLayer::new( + TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(), + Position::new(position, Dimension::new(262144).unwrap()).unwrap(), + LayerId::new(layer, Dimension::new(48).unwrap()).unwrap(), + ) +} + +#[test] +#[ignore = "root schedules one changed retained GDN projection/convolution/QK/readout/Z/outnorm/Out proof"] +fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let ctx = device.create_context(208 * 1024 * 1024).unwrap(); + let binding = BindingIdentity::test_identity(); // Identity tag only, never a ModelBinding. + let failed = Rc::new(Cell::new(false)); + let foreign = device.create_context(208 * 1024 * 1024).unwrap(); + for zero in [false, true] { + let owner = GdnOwner::new(); + let prior = GdnPrior::zero(binding.clone(), &owner, identity(0, 0).layer()).unwrap(); + let mut mirror = GdnStateMirror::new(binding.clone(), 0, &ctx, failed.clone()).unwrap(); + let mut chain = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); + let input: Vec = (0..2560) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + ((i % 17) as f32 - 8.) / 128. + } + }) + .collect(); + let input_bytes: Vec = input.iter().flat_map(|v| v.to_le_bytes()).collect(); + let source = upload(&ctx, &input).unwrap(); + let history: Vec = (0..HISTORY_ELEMENTS) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + ((i % 13) as f32 - 6.) / 256. + } + }) + .collect(); + let conv: Vec = (0..4 * CHANNELS) + .map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]) + .collect(); + let conv_buffer = upload(&ctx, &conv).unwrap(); + let dt = [-2.; 48]; + let a = [1.; 48]; + let dt_buffer = upload(&ctx, &dt).unwrap(); + let a_buffer = upload(&ctx, &a).unwrap(); + let gamma = [1.; 128]; + let gamma_buffer = upload(&ctx, &gamma).unwrap(); + let (qkv, expected_qkv) = pair_projection(&mut chain, &source, &input, Role::Qkv, 0); + let expected_conv = convolve(&ctx, &history, &expected_qkv, &conv, None).unwrap(); + let history_product = chain.upload(Role::History, &history).unwrap(); + let (next_history, h) = chain + .convolve(&history_product, &qkv, &conv_buffer) + .unwrap(); + exact(next_history.values(), &expected_conv.0); + exact(h.values(), &expected_conv.1); + let expected_qk = normalize_qk(&ctx, &expected_conv.1, 1e-6).unwrap(); + let qk = chain.normalize_qk(&h, 1e-6).unwrap(); + exact(qk.values(), &expected_qk); + let (alpha, expected_alpha) = pair_projection(&mut chain, &source, &input, Role::Alpha, 1); + let (beta_raw, expected_beta_raw) = + pair_projection(&mut chain, &source, &input, Role::BetaRaw, 2); + let expected_gates = + gates(&ctx, &expected_alpha, &expected_beta_raw, &dt, &a, None).unwrap(); + let (gate, beta) = chain + .gates(&alpha, &beta_raw, &dt_buffer, &a_buffer) + .unwrap(); + exact(gate.values(), &expected_gates.0); + exact(beta.values(), &expected_gates.1); + if !zero { + assert_eq!( + chain.buffer(&qkv, Role::Z).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!( + chain.validate(&foreign, &binding, identity(0, 0)), + Err(Error::IdentityMismatch) + ); + assert_eq!( + chain.validate(&ctx, &BindingIdentity::test_identity(), identity(0, 0)), + Err(Error::IdentityMismatch) + ); + assert_eq!( + chain.validate(&ctx, &binding, identity(0, 1)), + Err(Error::IdentityMismatch) + ); + let charge = ctx.allocated_bytes(); + let mut bad_conv = conv.clone(); + bad_conv[4 * CHANNELS - 1] = f32::from_bits(0x7fc00001); + let bad = upload_bytes( + &ctx, + &bad_conv + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>(), + ); + assert_eq!( + chain.convolve(&history_product, &qkv, &bad).err(), + Some(Error::NonFinite) + ); + bad.release().unwrap(); + assert_eq!(ctx.allocated_bytes(), charge); + assert!(!failed.get()); + } + let expected_recur = recur( + &ctx, + prior.values(), + &expected_qk[..2048], + &expected_qk[2048..4096], + &expected_conv.1[4096..], + &expected_gates.0, + &expected_gates.1, + ) + .unwrap(); + // Mandatory drain changes epoch and removes every pre-recurrence buffer. + chain.drain().unwrap(); + if !zero { + assert_eq!( + chain.buffer(&qkv, Role::Qkv).err(), + Some(Error::IdentityMismatch) + ); + } + if !zero { + // Genuine recurrence output with a different step-local epoch cannot + // enter this chain, and refusal must free its actual readout buffer. + let charge = ctx.allocated_bytes(); + let (foreign_scope, discarded_next) = mirror + .compute_retained( + &prior, + identity(0, 0), + Rc::new(()), + [ + &expected_qk[..2048], + &expected_qk[2048..4096], + &expected_conv.1[4096..], + &expected_gates.0, + &expected_gates.1, + ], + ) + .unwrap(); + assert_eq!( + chain.import_readout(foreign_scope, &prior).err(), + Some(Error::IdentityMismatch) + ); + mirror.discard(discarded_next).unwrap(); + assert_eq!(ctx.allocated_bytes(), charge); + assert!(!failed.get()); + } + let (carrier, next) = mirror + .compute_retained( + &prior, + identity(0, 0), + chain.scope_key(), + [ + &expected_qk[..2048], + &expected_qk[2048..4096], + &expected_conv.1[4096..], + &expected_gates.0, + &expected_gates.1, + ], + ) + .unwrap(); + let readout = chain.import_readout(carrier, &prior).unwrap(); + exact(readout.values(), &expected_recur.1); + let (z, expected_z) = pair_projection(&mut chain, &source, &input, Role::Z, 3); + let expected_normalized = + out_norm(&ctx, &expected_recur.1, &expected_z, &gamma, 1e-6, None).unwrap(); + let normalized = chain.out_norm(&readout, &z, &gamma_buffer, 1e-6).unwrap(); + exact(normalized.values(), &expected_normalized); + let out_bytes = matrix(2560, VALUES, 4); + let mut weights = upload_bytes(&ctx, &out_bytes); + let expected_out = original_projection(&ctx, &weights, &expected_normalized, 2560); + let actual_out = chain + .project_out(&weights, GdnMatrixKind::Bf16, &normalized) + .unwrap(); + exact(actual_out.values(), &expected_out); + let mut immutable = vec![0; out_bytes.len()]; + weights.copy_to(&mut immutable).unwrap(); + assert_eq!(immutable, out_bytes); + if !zero { + let charge = ctx.allocated_bytes(); + let end = immutable.len(); + immutable[end - 2..].copy_from_slice(&0x7fc1u16.to_le_bytes()); + weights.copy_from(&immutable).unwrap(); + assert_eq!( + chain + .project_out(&weights, GdnMatrixKind::Bf16, &normalized) + .err(), + Some(Error::NonFinite) + ); + assert_eq!(ctx.allocated_bytes(), charge); + assert!(!failed.get()); + } + let pending = mirror + .publish(next, identity(0, 0), expected_conv.0.clone()) + .unwrap(); + let committed = pending.into_prior(); + exact(committed.values(), &expected_recur.0); + exact(committed.history(), &expected_conv.0); + assert!(prior.values().iter().all(|v| v.to_bits() == 0)); + weights.release().unwrap(); + let mut unchanged_input = vec![0; input_bytes.len()]; + source.copy_to(&mut unchanged_input).unwrap(); + assert_eq!(unchanged_input, input_bytes); + release([source, conv_buffer, dt_buffer, a_buffer, gamma_buffer]).unwrap(); + chain.finish().unwrap(); + mirror.close().unwrap(); + assert_eq!(ctx.allocated_bytes(), 0); + assert!(!failed.get()); + println!("GDN_CHAIN PAIR zero={zero} exact_intermediate_and_state_words=899776"); + } + let mut chain = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); + assert_eq!( + Chain::new(&ctx, binding.clone(), identity(3, 0), failed.clone()).err(), + Some(Error::InvalidLayer) + ); + assert_eq!( + chain.upload(Role::Readout, &vec![0.; VALUES]).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!( + chain.upload(Role::Input, &[0.; 2559]).err(), + Some(Error::InvalidDimension) + ); + let mut bad = vec![0.; 2560]; + bad[2559] = f32::NAN; + assert_eq!( + chain.upload(Role::Input, &bad).err(), + Some(Error::NonFinite) + ); + let input = chain.upload(Role::Input, &[0.; 2560]).unwrap(); + let other = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); + assert_eq!( + other.buffer(&input, Role::Input).err(), + Some(Error::IdentityMismatch) + ); + other.finish().unwrap(); + let charge = ctx.allocated_bytes(); + failed.set(true); // Explicit shared policy, not injected CUDA failure. + assert_eq!( + chain.buffer(&input, Role::Input).err(), + Some(Error::CudaExecution) + ); + assert_eq!( + chain.upload(Role::Input, &[0.; 2560]).err(), + Some(Error::CudaExecution) + ); + assert_eq!( + Chain::new(&ctx, binding, identity(0, 0), failed.clone()).err(), + Some(Error::CudaExecution) + ); + assert_eq!(ctx.allocated_bytes(), charge); + drop(chain); // Sticky abandoned-chain cleanup must free all actual owners. + assert!(failed.get()); + assert_eq!(ctx.allocated_bytes(), 0); + assert_eq!(foreign.allocated_bytes(), 0); + ctx.synchronize().unwrap(); + ctx.close().unwrap(); + foreign.close().unwrap(); + println!("GDN_CHAIN COMPLETE finite_cases=2 exact_words=1799552 guard_refusals=16 allocated=0"); +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs index ae7908ea..4e2c153f 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs @@ -31,6 +31,71 @@ pub(super) struct MirrorNext<'ctx> { values: Box<[f32]>, } +/// Only the recurrence producer can pair this buffer with its finite readback. +pub(super) struct MirrorReadout<'ctx> { + context: &'ctx Context<'ctx>, + source: GdnPrior, + identity: Option, + scope: Option>, + buffer: Option>, + values: Option>, + failed: Rc>, +} +impl<'ctx> MirrorReadout<'ctx> { + pub(super) fn into_parts( + mut self, + context: &Context<'_>, + failed: &Rc>, + prior: &GdnPrior, + identity: TokenLayer, + scope: &Rc<()>, + ) -> Result<(DeviceBuffer<'ctx>, Box<[f32]>)> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) + || !Rc::ptr_eq(&self.failed, failed) + || !self.source.same_state(prior) + || self.identity != Some(identity) + || self + .scope + .as_ref() + .is_none_or(|key| !Rc::ptr_eq(key, scope)) + { + return Err(Error::IdentityMismatch); + } + if self.buffer.as_ref().is_none_or(|b| b.len() != VALUES * 4) { + return Err(Error::InvalidDimension); + } + validate_values( + self.values.as_deref().ok_or(Error::IdentityMismatch)?, + VALUES, + )?; + Ok(( + self.buffer.take().ok_or(Error::IdentityMismatch)?, + self.values.take().ok_or(Error::IdentityMismatch)?, + )) + } + fn into_host(mut self) -> Result> { + if let Some(buffer) = self.buffer.take() { + buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + })?; + } + self.values.take().ok_or(Error::IdentityMismatch) + } +} +impl Drop for MirrorReadout<'_> { + fn drop(&mut self) { + if let Some(buffer) = self.buffer.take() + && buffer.release().is_err() + { + self.failed.set(true); + } + } +} + impl<'ctx> GdnStateMirror<'ctx> { pub(in crate::qwen_forward) fn new( binding: BindingIdentity, @@ -77,6 +142,42 @@ impl<'ctx> GdnStateMirror<'ctx> { gate: &[f32], beta: &[f32], ) -> Result<(Box<[f32]>, MirrorNext<'ctx>)> { + let (readout, next) = self.compute_inner(prior, q, k, v, gate, beta)?; + match readout.into_host() { + Ok(values) => Ok((values, next)), + Err(primary) => { + let _ = self.discard(next); + Err(primary) + } + } + } + + pub(super) fn compute_retained( + &mut self, + prior: &GdnPrior, + identity: TokenLayer, + scope: Rc<()>, + inputs: [&[f32]; 5], + ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { + if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() { + return Err(Error::IdentityMismatch); + } + let (mut readout, next) = + self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?; + readout.identity = Some(identity); + readout.scope = Some(scope); + Ok((readout, next)) + } + + fn compute_inner( + &mut self, + prior: &GdnPrior, + q: &[f32], + k: &[f32], + v: &[f32], + gate: &[f32], + beta: &[f32], + ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { if self.failed.get() { return Err(Error::CudaExecution); } @@ -145,12 +246,6 @@ impl<'ctx> GdnStateMirror<'ctx> { )) })(); let mut cleanup = None; - if let Some(buffer) = output - && let Err(error) = buffer.release() - { - self.failed.set(true); - cleanup.get_or_insert(driver_error(error)); - } for buffer in temporary { if let Err(error) = buffer.release() { self.failed.set(true); @@ -163,7 +258,15 @@ impl<'ctx> GdnStateMirror<'ctx> { }; match result { Ok((state, readout)) => Ok(( - readout, + MirrorReadout { + context: self.context, + source: prior.clone(), + identity: None, + scope: None, + buffer: output.take(), + values: Some(readout), + failed: self.failed.clone(), + }, MirrorNext { context: self.context, source: prior.clone(), @@ -180,6 +283,11 @@ impl<'ctx> GdnStateMirror<'ctx> { { self.failed.set(true); } + if let Some(buffer) = output + && buffer.release().is_err() + { + self.failed.set(true); + } Err(primary) } } diff --git a/crates/leleka-runtime/src/qwen_forward/mtp.rs b/crates/leleka-runtime/src/qwen_forward/mtp.rs index 0dadc56f..7e51bcf0 100644 --- a/crates/leleka-runtime/src/qwen_forward/mtp.rs +++ b/crates/leleka-runtime/src/qwen_forward/mtp.rs @@ -11,7 +11,7 @@ use super::{ }; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, MtpKind, MtpRole}; use leleka_cuda_driver::{ - Bf16ProjectionShape, Context, DenseFormat, ProjectionKind, ProjectionSpec, + Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, ProjectionKind, ProjectionSpec, }; use std::{cell::Cell, rc::Rc}; #[path = "mtp_state.rs"] @@ -186,12 +186,19 @@ pub(super) fn step( output: &super::output::OutputStage<'_, '_>, cache: &MoeWeightCache<'_>, ) -> Result { + let transport_failed = Rc::new(Cell::new(false)); let result = (|| { input.frame.validate(binding, session)?; draft.prior(&input.frame)?; let read = super::mtp_gr::attention_read(binding, &input, session, cache)?; - let attention = - super::mtp_attention::MtpAttentionStage::run(binding, &read, draft, session, cache)?; + let attention = super::mtp_attention::MtpAttentionStage::run( + binding, + &read, + draft, + session, + cache, + Rc::clone(&transport_failed), + )?; let mlp = super::mtp_gr::mlp_read(binding, &attention, session, cache)?; let block = super::mtp_experts::MtpExpertStage::run(binding, &mlp, session, cache)?; let final_mixed = super::mtp_gr::finalize(binding, &block, &mlp, session, cache)?; @@ -217,6 +224,9 @@ pub(super) fn step( streams: streams.into_boxed_slice(), }) })(); + if transport_failed.get() { + session.note_mtp_failure(&Error::CudaExecution); + } if let Err(error) = &result { session.note_mtp_failure(error); } @@ -334,3 +344,62 @@ pub(super) fn project( cleanup?; Ok(output) } + +// Closed AttentionOutput consumer: only the matching actual MTP gated product +// supplies activation. The ordinary host-vector project() above stays unchanged. +pub(super) fn project_attention_output( + context: &Context<'_>, + binding: &ModelBinding, + session: &QwenSession<'_>, + input: &super::mtp_attention::MtpGated<'_>, + cache: &MoeWeightCache<'_>, +) -> Result> { + input.validate(binding, session)?; + if !std::ptr::eq(session.mtp_context()?, context) { + return Err(Error::IdentityMismatch); + } + let (kind, rows, columns, weights) = + cache.mtp_matrix(binding, context, MtpRole::AttentionOutput)?; + if (kind, rows, columns) != (MtpKind::Q8_0, 2560, 6144) { + return Err(Error::InvalidDimension); + } + project_attention_out_numeric(context, weights, input.numeric()) +} +pub(super) fn project_attention_out_numeric( + context: &Context<'_>, + weights: &DeviceBuffer<'_>, + input: &super::mtp_attention::RetainedGated<'_>, +) -> Result> { + const ROWS: usize = 2560; + const COLUMNS: usize = 6144; + let activation = input.buffer(context)?; + // Activation is already charged by Context. Reserve the same remaining + // output/quantizer/status increment as the original upload-based path. + preflight(context, ROWS * 4 + COLUMNS / 32 * 36 + 4)?; + let mut y = allocate(context, ROWS)?; + let result = (|| { + context + .project_q8_1( + weights, + activation, + &mut y, + ProjectionSpec { + rows: ROWS, + columns: COLUMNS, + kind: ProjectionKind::Dense(DenseFormat::Q8_0), + }, + ) + .map_err(driver_error)?; + download(&y, ROWS) + })(); + if result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { + input.failure_flag().set(true); + } + let cleanup = y.release().map_err(driver_error); + if cleanup.is_err() { + input.failure_flag().set(true); + } + let output = result?; + cleanup?; + Ok(output) +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs b/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs index 612c916c..38e9b424 100644 --- a/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs +++ b/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs @@ -3,7 +3,10 @@ use super::moe_weight_cache::MoeWeightCache; use super::{ contract::{Error, Result, Stage}, - mtp::{DenseKv, MtpFrame, MtpSession, f32_weights, preflight, project, reserve}, + mtp::{ + DenseKv, MtpFrame, MtpSession, f32_weights, preflight, project, project_attention_output, + reserve, + }, mtp_gr::MtpAttentionRead, qsa_index::{ allocate, binding_error, download, download_bytes, driver_error, release, upload, @@ -13,6 +16,7 @@ use super::{ }; use crate::model_binding::qwen4exp_input::{ModelBinding, MtpKind, MtpRole}; use leleka_cuda_driver::{Context, DeviceBuffer}; +use std::{cell::Cell, rc::Rc}; const N: usize = 2560; const Q: usize = 24 * 256; const KV: usize = 2 * 256; @@ -55,6 +59,7 @@ impl MtpAttentionStage { draft: &MtpSession, session: &QwenSession<'_>, cache: &MoeWeightCache<'_>, + failed: Rc>, ) -> Result { input.frame().validate(binding, session)?; let prior = draft.prior(input.frame())?; @@ -112,9 +117,15 @@ impl MtpAttentionStage { let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?; let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?; let q = norm_rope(context, &q, &qgamma, qw, geometry.position, true)?; - let attention = attend(context, &q, &keys, &values, &geometry)?; - let gated = apply_gate(context, &attention, &gate)?; - let output = project(context, binding, MtpRole::AttentionOutput, &gated, cache)?; + let attention = attend_retained(context, &q, &keys, &values, &geometry, failed)?; + let gated = MtpGated { + frame: input.frame().clone(), + numeric: gate_retained(context, attention, &gate)?, + }; + let result = project_attention_output(context, binding, session, &gated, cache); + let cleanup = gated.close(); + let output = result?; + cleanup?; validate_values(&output, N)?; input.frame().validate(binding, session)?; draft.prior(input.frame())?; @@ -133,6 +144,227 @@ impl MtpAttentionStage { }) } } +// Only the real attention/gate helpers can construct these numeric owners. +// Host readbacks are canonical finite witnesses of these exact buffers. +pub(super) struct MtpGated<'ctx> { + frame: MtpFrame, + numeric: RetainedGated<'ctx>, +} +impl MtpGated<'_> { + pub(super) fn validate(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> { + self.frame.validate(binding, session) + } + pub(super) fn numeric(&self) -> &RetainedGated<'_> { + &self.numeric + } + fn close(self) -> Result<()> { + self.numeric.close() + } +} +struct RetainedAttended<'ctx> { + context: &'ctx Context<'ctx>, + buffer: Option>, + values: Box<[f32]>, + failed: Rc>, +} +impl RetainedAttended<'_> { + fn values(&self) -> &[f32] { + &self.values + } + #[cfg(test)] + fn close(mut self) -> Result<()> { + close_transport(self.buffer.take(), &self.failed) + } +} +impl Drop for RetainedAttended<'_> { + fn drop(&mut self) { + let _ = release_transport([self.buffer.take()], &self.failed); + } +} +pub(super) struct RetainedGated<'ctx> { + context: &'ctx Context<'ctx>, + buffer: Option>, + values: Box<[f32]>, + failed: Rc>, +} +impl RetainedGated<'_> { + pub(super) fn values(&self) -> &[f32] { + &self.values + } + pub(super) fn buffer(&self, context: &Context<'_>) -> Result<&DeviceBuffer<'_>> { + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + if self.failed.get() { + return Err(Error::CudaExecution); + } + let buffer = self.buffer.as_ref().ok_or(Error::CudaExecution)?; + if buffer.len() != Q * 4 { + return Err(Error::InvalidDimension); + } + validate_values(self.values(), Q)?; + Ok(buffer) + } + pub(super) fn failure_flag(&self) -> &Cell { + &self.failed + } + pub(super) fn close(mut self) -> Result<()> { + close_transport(self.buffer.take(), &self.failed) + } +} +impl Drop for RetainedGated<'_> { + fn drop(&mut self) { + let _ = release_transport([self.buffer.take()], &self.failed); + } +} +fn release_transport( + buffers: [Option>; C], + failed: &Cell, +) -> Result<()> { + let mut error = None; + for buffer in buffers.into_iter().flatten() { + if let Err(e) = buffer.release().map_err(attention_driver_error) { + failed.set(true); + error.get_or_insert(e); + } + } + error.map_or(Ok(()), Err) +} +fn close_transport(buffer: Option>, failed: &Cell) -> Result<()> { + let primary = failed.get().then_some(Error::CudaExecution); + let cleanup = release_transport([buffer], failed); + primary.map_or(cleanup, Err) +} +fn note_transport(result: &Result, failed: &Cell) { + if result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { + failed.set(true); + } +} +fn upload_transport<'ctx>( + context: &'ctx Context<'ctx>, + bytes: &[u8], + failed: &Cell, +) -> Result> { + if failed.get() { + return Err(Error::CudaExecution); + } + let mut buffer = context + .allocate(bytes.len()) + .map_err(attention_driver_error)?; + let copy = buffer.copy_from(bytes).map_err(attention_driver_error); + note_transport(©, failed); + if let Err(primary) = copy { + let _ = release_transport([Some(buffer)], failed); + return Err(primary); + } + Ok(buffer) +} +fn upload_transport_f32<'ctx>( + context: &'ctx Context<'ctx>, + values: &[f32], + failed: &Cell, +) -> Result> { + let mut bytes = reserve(values.len().checked_mul(4).ok_or(Error::Overflow)?)?; + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } + upload_transport(context, &bytes, failed) +} +fn attend_retained<'ctx>( + context: &'ctx Context<'ctx>, + query: &[f32], + keys: &[u8], + values: &[u8], + geometry: &DenseGeometry, + failed: Rc>, +) -> Result> { + if failed.get() { + return Err(Error::CudaExecution); + } + validate_values(query, Q)?; + validate_window(keys, values, geometry)?; + preflight(context, geometry.device_bytes)?; + let (mut q, mut k, mut v, mut y) = (None, None, None, None); + let result = (|| { + q = Some(upload_transport_f32(context, query, &failed)?); + k = Some(upload_transport(context, keys, &failed)?); + v = Some(upload_transport(context, values, &failed)?); + y = Some(allocate(context, Q)?); + context + .mtp_dense_attend_f16( + q.as_ref().ok_or(Error::CudaExecution)?, + k.as_ref().ok_or(Error::CudaExecution)?, + v.as_ref().ok_or(Error::CudaExecution)?, + y.as_mut().ok_or(Error::CudaExecution)?, + geometry.position, + ) + .map_err(attention_driver_error)?; + download(y.as_ref().ok_or(Error::CudaExecution)?, Q) + })(); + note_transport(&result, &failed); + let cleanup = release_transport([q, k, v], &failed); + if result.is_err() || cleanup.is_err() { + let y_cleanup = release_transport([y], &failed); + let _ = result?; + cleanup?; + y_cleanup?; + return Err(Error::CudaExecution); + } + Ok(RetainedAttended { + context, + buffer: y, + values: result?, + failed, + }) +} +fn gate_retained<'ctx>( + context: &'ctx Context<'ctx>, + mut attended: RetainedAttended<'ctx>, + gate: &[f32], +) -> Result> { + let failed = Rc::clone(&attended.failed); + let (mut gate_buffer, mut gated) = (None, None); + let result = (|| { + if !std::ptr::eq(attended.context, context) { + return Err(Error::IdentityMismatch); + } + if failed.get() { + return Err(Error::CudaExecution); + } + validate_values(attended.values(), Q)?; + validate_values(gate, Q)?; + let source = attended.buffer.as_ref().ok_or(Error::CudaExecution)?; + if source.len() != Q * 4 { + return Err(Error::InvalidDimension); + } + gate_buffer = Some(upload_transport_f32(context, gate, &failed)?); + gated = Some(allocate(context, Q)?); + context + .qsa_gate_f32( + source, + gate_buffer.as_ref().ok_or(Error::CudaExecution)?, + gated.as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(attention_driver_error)?; + download(gated.as_ref().ok_or(Error::CudaExecution)?, Q) + })(); + note_transport(&result, &failed); + let cleanup = release_transport([attended.buffer.take(), gate_buffer], &failed); + if result.is_err() || cleanup.is_err() { + let gated_cleanup = release_transport([gated], &failed); + let _ = result?; + cleanup?; + gated_cleanup?; + return Err(Error::CudaExecution); + } + Ok(RetainedGated { + context, + buffer: gated, + values: result?, + failed, + }) +} + fn attention_driver_error(error: leleka_cuda_driver::Error) -> Error { match driver_error(error) { Error::Unsupported(_) => Error::Unsupported(Stage::QsaAttention), @@ -318,6 +550,10 @@ fn apply_gate(context: &Context<'_>, values: &[f32], gate: &[f32]) -> Result Vec { + let mut bytes = Vec::with_capacity(16_711_680); + for row in 0..2560 { + for block in 0..192 { + bytes.extend_from_slice(&0x1c00u16.to_le_bytes()); // exact F16 2^-8 + for lane in 0..32 { + let column = block * 32 + lane; + let code = ((row + 3 * column) % 11) as i8 - 5; + bytes.push(code as u8); + } + } + } + assert_eq!(bytes.len(), 16_711_680); + bytes +} + +fn half_kv(width: usize, zero: bool) -> (Vec, Vec) { + // Original dense qsa_decode_attn.cu layout: ((cell*2+head)*256+dimension). + const KEY: [u16; 6] = [0x0000, 0x3400, 0xb800, 0x3a00, 0xbc00, 0x3800]; + const VALUE: [u16; 6] = [0x3c00, 0xbc00, 0x4000, 0xb800, 0x3400, 0x4200]; + let keys = (0..width * 512) + .flat_map(|i| KEY[(i * 7 + i / 256) % 6].to_le_bytes()) + .collect(); + let values = (0..width * 512) + .flat_map(|i| { + let word = if zero { + if i % 2 == 0 { 0x8000u16 } else { 0 } + } else { + VALUE[(i * 11 + i / 512) % 6] + }; + word.to_le_bytes() + }) + .collect(); + (keys, values) +} + +type Legacy = (Box<[f32]>, Box<[f32]>, Box<[f32]>); +fn original_transfer_chain( + context: &Context<'_>, + query: &[f32], + keys: &[u8], + values: &[u8], + gate: &[f32], + position: u32, + matrix: &DeviceBuffer<'_>, +) -> Legacy { + let q = upload(context, query).unwrap(); + let k = upload_bytes(context, keys).unwrap(); + let v = upload_bytes(context, values).unwrap(); + let mut y = allocate(context, Q).unwrap(); + context + .mtp_dense_attend_f16(&q, &k, &v, &mut y, position) + .unwrap(); + let attended = download(&y, Q).unwrap(); + release([q, k, v, y]).unwrap(); + let a = upload(context, &attended).unwrap(); + let g = upload(context, gate).unwrap(); + let mut y = allocate(context, Q).unwrap(); + context.qsa_gate_f32(&a, &g, &mut y).unwrap(); + let gated = download(&y, Q).unwrap(); + release([a, g, y]).unwrap(); + let a = upload(context, &gated).unwrap(); + let mut y = allocate(context, 2560).unwrap(); + context + .project_q8_1( + matrix, + &a, + &mut y, + ProjectionSpec { + rows: 2560, + columns: Q, + kind: ProjectionKind::Dense(DenseFormat::Q8_0), + }, + ) + .unwrap(); + let out = download(&y, 2560).unwrap(); + release([a, y]).unwrap(); + (attended, gated, out) +} + +#[test] +#[ignore = "root schedules one changed MTP attended/gated/Out transport proof"] +fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let context = device.create_context(160 * 1024 * 1024).unwrap(); + let failed = Rc::new(Cell::new(false)); + let weights = out_weights(); + let matrix = upload_bytes(&context, &weights).unwrap(); + for (position, zero) in [(0u32, false), (64, true)] { + let shape = geometry(u64::from(position)).unwrap(); + let width = shape.width; + let query: Vec = (0..Q) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + (i % 17) as f32 / 64. - 8. / 64. + } + }) + .collect(); + let gate: Vec = (0..Q) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + (i % 13) as f32 / 8. - 6. / 8. + } + }) + .collect(); + let query_bits: Vec = query.iter().map(|v| v.to_bits()).collect(); + let gate_bits: Vec = gate.iter().map(|v| v.to_bits()).collect(); + let (keys, values) = half_kv(width, zero); + let legacy = + original_transfer_chain(&context, &query, &keys, &values, &gate, position, &matrix); + let charged = context.allocated_bytes(); + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + exact(attended.values(), &legacy.0); + assert_eq!(context.allocated_bytes(), charged + Q * 4); + let gated = gate_retained(&context, attended, &gate).unwrap(); + exact(gated.values(), &legacy.1); + assert_eq!(context.allocated_bytes(), charged + Q * 4); + let mut actual_bytes = vec![0; Q * 4]; + gated + .buffer(&context) + .unwrap() + .copy_to(&mut actual_bytes) + .unwrap(); + assert_eq!( + actual_bytes, + legacy + .1 + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>() + ); + let actual = + super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).unwrap(); + exact(&actual, &legacy.2); + gated.close().unwrap(); + assert_eq!(context.allocated_bytes(), charged); + assert_eq!( + query.iter().map(|v| v.to_bits()).collect::>(), + query_bits + ); + assert_eq!( + gate.iter().map(|v| v.to_bits()).collect::>(), + gate_bits + ); + println!("MTP_RETAINED PAIR width={width} zero={zero} exact_words=14848"); + } + let mut unchanged = vec![0; weights.len()]; + matrix.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, weights); + matrix.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + + let query = vec![0.125; Q]; + let gate = vec![0.25; Q]; + let (keys, values) = half_kv(1, false); + let shape = geometry(0).unwrap(); + assert_eq!( + attend_retained( + &context, + &query[..Q - 1], + &keys, + &values, + &shape, + failed.clone() + ) + .err(), + Some(Error::InvalidDimension) + ); + let mut bad_query = query.clone(); + bad_query[Q - 1] = f32::from_bits(0x7fc00001); + assert_eq!( + attend_retained(&context, &bad_query, &keys, &values, &shape, failed.clone()).err(), + Some(Error::NonFinite) + ); + assert_eq!( + attend_retained( + &context, + &query, + &keys[..1022], + &values, + &shape, + failed.clone() + ) + .err(), + Some(Error::InvalidDimension) + ); + let mut bad_keys = keys.clone(); + bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes()); + assert_eq!( + attend_retained(&context, &query, &bad_keys, &values, &shape, failed.clone()).err(), + Some(Error::NonFinite) + ); + let mut bad_values = values.clone(); + bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes()); + assert_eq!( + attend_retained(&context, &query, &keys, &bad_values, &shape, failed.clone()).err(), + Some(Error::NonFinite) + ); + // All operands are finite, but the original F32 dot overflows. The actual + // retained attention's full D2H rejects before a gate can mask the failure. + assert_eq!( + attend_retained( + &context, + &vec![f32::MAX; Q], + &0x7bffu16.to_le_bytes().repeat(512), + &values, + &shape, + failed.clone() + ) + .err(), + Some(Error::NonFinite) + ); + assert_eq!(context.allocated_bytes(), 0); + assert!(!failed.get()); + + // Successful abandoned owners exercise the new Drop fallback. This is + // ownership/abort evidence only, not an additional numeric oracle pair. + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + attended.close().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let abandoned = gate_retained(&context, attended, &gate).unwrap(); + assert_eq!(context.allocated_bytes(), Q * 4); + drop(abandoned); + assert_eq!(context.allocated_bytes(), 0); + assert!(!failed.get()); + + let foreign = device.create_context(160 * 1024 * 1024).unwrap(); + let mut bad_gate = gate.clone(); + bad_gate[Q - 1] = f32::NAN; + for malformed in [&bad_gate[..], &gate[..Q - 1]] { + let expected = if malformed.len() == Q { + Error::NonFinite + } else { + Error::InvalidDimension + }; + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + assert_eq!( + gate_retained(&context, attended, malformed).err(), + Some(expected) + ); + assert_eq!(context.allocated_bytes(), 0); + } + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + assert_eq!( + gate_retained(&foreign, attended, &gate).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!(context.allocated_bytes(), 0); + assert_eq!(foreign.allocated_bytes(), 0); + + let attended = + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let gated = gate_retained(&context, attended, &gate).unwrap(); + assert_eq!(gated.buffer(&foreign).err(), Some(Error::IdentityMismatch)); + let malformed = upload_bytes(&context, &[0; 2]).unwrap(); + let charged = context.allocated_bytes(); + assert_eq!( + super::super::mtp::project_attention_out_numeric(&context, &malformed, &gated).err(), + Some(Error::InvalidDimension) + ); + assert_eq!(context.allocated_bytes(), charged); + malformed.release().unwrap(); + let mut bad_weights = out_weights(); + let end = bad_weights.len(); + bad_weights[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes()); + let matrix = upload_bytes(&context, &bad_weights).unwrap(); + let charged = context.allocated_bytes(); + assert_eq!( + super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).err(), + Some(Error::NonFinite) + ); + assert_eq!(context.allocated_bytes(), charged); + assert!(!failed.get()); + // Explicit shared-policy flag, not injected device failure. No operation + // may clear it; teardown still frees the actual successful owner and matrix. + failed.set(true); + assert_eq!( + attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).err(), + Some(Error::CudaExecution) + ); + assert_eq!(gated.buffer(&context).err(), Some(Error::CudaExecution)); + assert_eq!( + super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).err(), + Some(Error::CudaExecution) + ); + assert_eq!(context.allocated_bytes(), charged); + assert_eq!(gated.close(), Err(Error::CudaExecution)); + matrix.release().unwrap(); + assert!(failed.get()); + assert_eq!(context.allocated_bytes(), 0); + context.synchronize().unwrap(); + context.close().unwrap(); + foreign.close().unwrap(); + println!( + "MTP_RETAINED COMPLETE exact_words=29696 finite_cases=2 guard_refusals=15 abort_cleanup_cases=2 allocated=0" + ); +}