diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs index a3cb49c1..c8256ff5 100644 --- a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs @@ -1,12 +1,16 @@ //! Actor-owned immutable selected-model weights. Numeric session state is separate. use super::contract::{Error, Result}; +use super::gdn::{ALL_MIRROR_BYTES, GdnStateMirror}; use super::qsa_index::{binding_error, driver_error}; use crate::model_binding::qwen4exp_input::{ BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, GrWeights, ModelBinding, PleMatrixRole, PleWeights, QsaMatrixKind, QsaMatrixRole, QsaWeights, }; use leleka_cuda_driver::{Context, DeviceBuffer}; -use std::{cell::Cell, rc::Rc}; +use std::{ + cell::{Cell, RefCell, RefMut}, + rc::Rc, +}; const RESERVE: usize = 128 * 1024 * 1024; #[derive(Clone, Copy, Default)] pub(crate) struct DenseCacheCounters { @@ -45,6 +49,8 @@ pub(crate) struct DenseWeightCache<'ctx> { context: &'ctx Context<'ctx>, buffers: Vec>, gdn: Vec>, + gdn_mirrors: Vec>>>, + mirror_failed: Rc>, qsa: Vec>, gr: Vec, router: Vec, @@ -63,6 +69,8 @@ impl<'ctx> DenseWeightCache<'ctx> { context, buffers: Vec::new(), gdn: Vec::new(), + gdn_mirrors: Vec::new(), + mirror_failed: Rc::new(Cell::new(false)), qsa: Vec::new(), gr: Vec::new(), router: Vec::new(), @@ -74,6 +82,10 @@ impl<'ctx> DenseWeightCache<'ctx> { .gdn .try_reserve_exact(n) .map_err(|_| Error::InputAllocation)?; + result + .gdn_mirrors + .try_reserve_exact(n) + .map_err(|_| Error::InputAllocation)?; result .qsa .try_reserve_exact(n) @@ -167,7 +179,20 @@ impl<'ctx> DenseWeightCache<'ctx> { } else { None }; + let mirror = gdn + .as_ref() + .map(|_| { + GdnStateMirror::new( + result.binding.clone(), + id, + context, + result.mirror_failed.clone(), + ) + }) + .transpose()? + .map(RefCell::new); result.gdn.push(gdn); + result.gdn_mirrors.push(mirror); result.qsa.push(qsa); for role in [GrRole::Attention(id), GrRole::Ffn(id)] { result.add_gr(binding, role)?; @@ -181,6 +206,14 @@ impl<'ctx> DenseWeightCache<'ctx> { } result.add_gr(binding, GrRole::Final)?; result.add_ple(binding)?; + let mirror_count = result + .gdn_mirrors + .iter() + .filter(|entry| entry.is_some()) + .count(); + if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) { + return Err(Error::InvalidDimension); + } result.validate(binding)?; Ok(()) })(); @@ -330,11 +363,13 @@ impl<'ctx> DenseWeightCache<'ctx> { binding.validate_ple_sources().map_err(binding_error) } fn check(&self, binding: &ModelBinding) -> Result<()> { - if self.binding.matches(&binding.identity()) { - Ok(()) - } else { - Err(Error::IdentityMismatch) + if !self.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); } + if self.mirror_failed.get() { + return Err(Error::CudaExecution); + } + Ok(()) } fn hit(&self) -> Result<()> { let mut c = self.counters.get(); @@ -350,6 +385,31 @@ impl<'ctx> DenseWeightCache<'ctx> { .and_then(Option::as_ref) .ok_or(Error::InvalidLayer) } + pub(super) fn gdn_mirror( + &self, + binding: &ModelBinding, + layer: u32, + context: &Context<'_>, + ) -> Result>> { + self.check(binding)?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + let resident = self + .gdn + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { + return Err(Error::IdentityMismatch); + } + self.gdn_mirrors + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch) + } pub(super) fn qsa(&self, binding: &ModelBinding, layer: u32) -> Result<&QsaResident> { self.check(binding)?; self.hit()?; @@ -507,7 +567,12 @@ impl<'ctx> DenseWeightCache<'ctx> { self.counters.get() } pub(crate) fn close(self) -> Result<()> { - let mut error = None; + let mut error = self.mirror_failed.get().then_some(Error::CudaExecution); + for mirror in self.gdn_mirrors.into_iter().flatten() { + if let Err(e) = mirror.into_inner().close() { + error.get_or_insert(e); + } + } for b in self.buffers { if let Err(e) = b.release() { error.get_or_insert(driver_error(e)); diff --git a/crates/leleka-runtime/src/qwen_forward/gdn.rs b/crates/leleka-runtime/src/qwen_forward/gdn.rs index 24cf98e1..cf0c7213 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn.rs @@ -15,7 +15,11 @@ use leleka_cuda_driver::{ }; #[path = "gdn_state.rs"] mod state; +use state::GdnStateKey; pub(super) use state::{GdnOwner, GdnPending, GdnPrior}; +#[path = "gdn_state_mirror.rs"] +mod mirror; +pub(super) use mirror::{ALL_MIRROR_BYTES, GdnStateMirror}; const WIDTH: usize = 128; const KEY_HEADS: usize = 16; const VALUE_HEADS: usize = 48; @@ -82,93 +86,137 @@ impl GdnStage { let context = txn.cuda_context()?; preflight_budget(context.budget_bytes(), context.allocated_bytes())?; let resident = cache.map(|c| c.gdn(binding, layer.get())).transpose()?; - let weights = if let Some(r) = resident { - r.weights.clone() - } else { - std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?) - }; - let aux = cache.zip(resident).map(|(c, r)| c.gdn_aux(r)).transpose()?; - let qkv = project( - context, - binding, - &weights, - GdnMatrixRole::Qkv, - input.mixed(), - cache, - )?; - let (history, h) = convolve( - context, - prior.history(), - &qkv, - weights.conv(), - aux.map(|v| v[0]), - )?; - let qk = normalize_qk(context, &h, weights.epsilon())?; - let alpha = project( - context, - binding, - &weights, - GdnMatrixRole::Alpha, - input.mixed(), - cache, - )?; - let beta_raw = project( - context, - binding, - &weights, - GdnMatrixRole::Beta, - input.mixed(), - cache, - )?; - let (gate, beta) = gates( - context, - &alpha, - &beta_raw, - weights.dt(), - weights.a(), - aux.map(|v| [v[1], v[2]]), - )?; - let (next_state, readout) = recur( - context, - prior.values(), - &qk[..2048], - &qk[2048..4096], - &h[4096..], - &gate, - &beta, - )?; - let z = project( - context, - binding, - &weights, - GdnMatrixRole::Z, - input.mixed(), - cache, - )?; - let normalized = out_norm( - context, - &readout, - &z, - weights.norm(), - weights.epsilon(), - aux.map(|v| v[3]), - )?; - let output = project( - context, - binding, - &weights, - GdnMatrixRole::Out, - &normalized, - cache, - )?; - validate_values(&output, 2560)?; - let pending = GdnPending::new(prior, input.identity(), next_state, history)?; - Ok(GdnReady { - identity: input.identity(), - binding: binding.identity(), - output, - pending: Some(pending), - }) + let mut mirror = cache + .map(|c| c.gdn_mirror(binding, layer.get(), context)) + .transpose()?; + let mut mirror_next = None; + let operation = (|| -> Result { + let weights = if let Some(r) = resident { + r.weights.clone() + } else { + std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?) + }; + let aux = cache.zip(resident).map(|(c, r)| c.gdn_aux(r)).transpose()?; + let qkv = project( + context, + binding, + &weights, + GdnMatrixRole::Qkv, + input.mixed(), + cache, + )?; + let (history, h) = convolve( + context, + prior.history(), + &qkv, + weights.conv(), + aux.map(|v| v[0]), + )?; + let qk = normalize_qk(context, &h, weights.epsilon())?; + let alpha = project( + context, + binding, + &weights, + GdnMatrixRole::Alpha, + input.mixed(), + cache, + )?; + let beta_raw = project( + context, + binding, + &weights, + GdnMatrixRole::Beta, + input.mixed(), + cache, + )?; + let (gate, beta) = gates( + context, + &alpha, + &beta_raw, + weights.dt(), + weights.a(), + aux.map(|v| [v[1], v[2]]), + )?; + let (next_state, readout) = if let Some(mirror) = mirror.as_deref_mut() { + let (readout, next) = mirror.compute( + prior, + &qk[..2048], + &qk[2048..4096], + &h[4096..], + &gate, + &beta, + )?; + mirror_next = Some(next); + (None, readout) + } else { + let (state, readout) = recur( + context, + prior.values(), + &qk[..2048], + &qk[2048..4096], + &h[4096..], + &gate, + &beta, + )?; + (Some(state), readout) + }; + let z = project( + context, + binding, + &weights, + GdnMatrixRole::Z, + input.mixed(), + cache, + )?; + let normalized = out_norm( + context, + &readout, + &z, + weights.norm(), + weights.epsilon(), + aux.map(|v| v[3]), + )?; + let output = project( + context, + binding, + &weights, + GdnMatrixRole::Out, + &normalized, + cache, + )?; + validate_values(&output, 2560)?; + let pending = if let Some(next) = mirror_next.take() { + mirror + .as_deref_mut() + .ok_or(Error::IdentityMismatch)? + .publish(next, input.identity(), history)? + } else { + GdnPending::new( + prior, + input.identity(), + next_state.ok_or(Error::IdentityMismatch)?, + history, + )? + }; + Ok(GdnReady { + identity: input.identity(), + binding: binding.identity(), + output, + pending: Some(pending), + }) + })(); + if let Some(next) = mirror_next { + // Downstream failures never publish a mirror key. Explicitly free + // the completed candidate; cleanup uncertainty poisons the cache. + let cleanup = mirror + .as_deref_mut() + .ok_or(Error::IdentityMismatch)? + .discard(next); + if operation.is_ok() { + cleanup?; + } + } + operation } } fn preflight_budget(budget: usize, allocated: usize) -> Result<()> { diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state.rs index eb66c5ec..0ed15746 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_state.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state.rs @@ -2,7 +2,7 @@ use super::super::contract::{Error, LayerId, Position, Result, TokenLayer}; use super::{HISTORY_ELEMENTS, STATE_ELEMENTS, validate_values}; use crate::model_binding::qwen4exp_input::BindingIdentity; -use std::rc::Rc; +use std::rc::{Rc, Weak}; #[derive(Clone)] pub(in crate::qwen_forward) struct GdnOwner(Rc<()>); @@ -24,7 +24,20 @@ struct State { } #[derive(Clone)] pub(in crate::qwen_forward) struct GdnPrior(Rc); +/// A weak, exact producer identity; numerical position is never a cache key. +pub(super) struct GdnStateKey(Weak); +impl GdnStateKey { + pub(super) fn matches(&self, prior: &GdnPrior) -> bool { + Weak::ptr_eq(&self.0, &Rc::downgrade(&prior.0)) + } +} impl GdnPrior { + pub(super) fn mirror_key(&self) -> GdnStateKey { + GdnStateKey(Rc::downgrade(&self.0)) + } + pub(super) fn mirror_admits(&self, binding: &BindingIdentity, layer: u32) -> bool { + self.0.binding.matches(binding) && self.layer().get() == layer + } #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] pub(in crate::qwen_forward) fn test_reset_replay_numeric_eq(&self, other: &Self) -> bool { self.layer() == other.layer() @@ -106,6 +119,10 @@ pub(in crate::qwen_forward) struct GdnPending { identity: TokenLayer, } impl GdnPending { + pub(super) fn mirror_next(&self, prior: &GdnPrior) -> Result<&GdnPrior> { + self.validate(prior, self.identity)?; + Ok(&self.next) + } pub(super) fn new( prior: &GdnPrior, identity: TokenLayer, diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs new file mode 100644 index 00000000..ae7908ea --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror.rs @@ -0,0 +1,298 @@ +//! One latest device recurrence per layer; immutable host state remains canonical. +use super::{ + BindingIdentity, Context, DeviceBuffer, Error, GdnPending, GdnPrior, GdnStateKey, Result, + STATE_ELEMENTS, TokenLayer, VALUES, allocate, download, driver_error, preflight_budget, + validate_values, +}; +use std::{cell::Cell, rc::Rc}; + +pub(super) const MIRROR_BYTES: usize = STATE_ELEMENTS * 4; +pub(in crate::qwen_forward) const ALL_MIRROR_BYTES: usize = 36 * MIRROR_BYTES; + +pub(in crate::qwen_forward) struct GdnStateMirror<'ctx> { + context: &'ctx Context<'ctx>, + binding: BindingIdentity, + layer: u32, + buffer: Option>, + key: Option, + failed: Rc>, + #[cfg(test)] + pub(super) hits: usize, + #[cfg(test)] + pub(super) misses: usize, +} + +/// Only compute can construct this candidate. Its source stays alive until +/// pending validation, but published mirrors retain only a weak state key. +pub(super) struct MirrorNext<'ctx> { + context: &'ctx Context<'ctx>, + source: GdnPrior, + buffer: DeviceBuffer<'ctx>, + values: Box<[f32]>, +} + +impl<'ctx> GdnStateMirror<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: BindingIdentity, + layer: u32, + context: &'ctx Context<'ctx>, + failed: Rc>, + ) -> Result { + if failed.get() { + return Err(Error::CudaExecution); + } + if layer >= 48 { + return Err(Error::InvalidLayer); + } + // Charge all fixed mirrors while the actor loads, before lazy MoE can + // consume the scratch reserve. Uninitialized placeholders cannot hit. + preflight_budget( + context.budget_bytes(), + context + .allocated_bytes() + .checked_add(MIRROR_BYTES) + .ok_or(Error::Overflow)?, + )?; + let buffer = context.allocate(MIRROR_BYTES).map_err(driver_error)?; + Ok(Self { + context, + binding, + layer, + buffer: Some(buffer), + key: None, + failed, + #[cfg(test)] + hits: 0, + #[cfg(test)] + misses: 0, + }) + } + + pub(super) fn compute( + &mut self, + prior: &GdnPrior, + q: &[f32], + k: &[f32], + v: &[f32], + gate: &[f32], + beta: &[f32], + ) -> Result<(Box<[f32]>, MirrorNext<'ctx>)> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !prior.mirror_admits(&self.binding, self.layer) { + return Err(Error::IdentityMismatch); + } + for (values, count) in [ + (prior.values(), STATE_ELEMENTS), + (q, 2048), + (k, 2048), + (v, VALUES), + (gate, 48), + (beta, 48), + ] { + validate_values(values, count)?; + } + let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; + if resident.len() != MIRROR_BYTES { + return Err(Error::InvalidDimension); + } + preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; + let hit = self.key.as_ref().is_some_and(|key| key.matches(prior)); + #[cfg(test)] + if hit { + self.hits += 1; + } else { + self.misses += 1; + } + let mut temporary = Vec::new(); + temporary + .try_reserve_exact(7) + .map_err(|_| Error::InputAllocation)?; + let mut next = None; + let mut output = None; + let operation = (|| -> Result { + // A rollback/reset miss uploads canonical host bytes into a + // transient prior; it never changes the identity of the mirror. + if !hit { + temporary.push(upload_checked(self.context, prior.values(), &self.failed)?); + } + let first = temporary.len(); + for values in [q, k, v, gate, beta] { + temporary.push(upload_checked(self.context, values, &self.failed)?); + } + next = Some(allocate(self.context, STATE_ELEMENTS)?); + output = Some(allocate(self.context, VALUES)?); + let state = if hit { resident } else { &temporary[0] }; + self.context + .gdn_step_f32( + state, + &temporary[first], + &temporary[first + 1], + &temporary[first + 2], + &temporary[first + 3], + &temporary[first + 4], + next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)?; + Ok(( + download( + next.as_ref().ok_or(Error::IdentityMismatch)?, + STATE_ELEMENTS, + )?, + download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, + )) + })(); + 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); + cleanup.get_or_insert(driver_error(error)); + } + } + let result = match operation { + Err(primary) => Err(primary), + Ok(values) => cleanup.map_or(Ok(values), Err), + }; + match result { + Ok((state, readout)) => Ok(( + readout, + MirrorNext { + context: self.context, + source: prior.clone(), + buffer: next.take().ok_or(Error::IdentityMismatch)?, + values: state, + }, + )), + Err(primary) => { + if primary == Error::CudaExecution { + self.failed.set(true); + } + if let Some(buffer) = next + && buffer.release().is_err() + { + self.failed.set(true); + } + Err(primary) + } + } + } + + pub(super) fn discard(&mut self, next: MirrorNext<'ctx>) -> Result<()> { + next.buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }) + } + + pub(super) fn publish( + &mut self, + next: MirrorNext<'ctx>, + identity: TokenLayer, + history: Box<[f32]>, + ) -> Result { + let MirrorNext { + context, + source, + buffer, + values, + } = next; + let admitted = (|| -> Result<(GdnStateKey, GdnPending)> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) + || buffer.len() != MIRROR_BYTES + || !source.mirror_admits(&self.binding, self.layer) + { + return Err(Error::IdentityMismatch); + } + // Only this producer owns the values downloaded from this exact + // candidate buffer. A caller cannot pair it with another payload. + let pending = GdnPending::new(&source, identity, values, history)?; + Ok((pending.mirror_next(&source)?.mirror_key(), pending)) + })(); + let (key, pending) = match admitted { + Ok(value) => value, + Err(primary) => { + let _ = self.release_buffer(buffer); + return Err(primary); + } + }; + // Never publish a hit key until replacement cleanup succeeded. + self.key = None; + let old = match self.buffer.take() { + Some(old) => old, + None => { + let _ = self.release_buffer(buffer); + return Err(Error::CudaExecution); + } + }; + if let Err(error) = old.release() { + self.failed.set(true); + let primary = driver_error(error); + let _ = self.release_buffer(buffer); + return Err(primary); + } + self.buffer = Some(buffer); + self.key = Some(key); + Ok(pending) + } + + fn release_buffer(&mut self, buffer: DeviceBuffer<'ctx>) -> Result<()> { + buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }) + } + + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.key = None; + match self.buffer.take() { + Some(buffer) => buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }), + None if self.failed.get() => Err(Error::CudaExecution), + None => Ok(()), + } + } +} + +fn upload_checked<'ctx>( + context: &'ctx Context<'ctx>, + values: &[f32], + failed: &Cell, +) -> Result> { + let size = values.len().checked_mul(4).ok_or(Error::Overflow)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(size) + .map_err(|_| Error::InputAllocation)?; + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } + let mut buffer = context.allocate(size).map_err(driver_error)?; + if let Err(error) = buffer.copy_from(&bytes) { + let primary = driver_error(error); + if primary == Error::CudaExecution { + failed.set(true); + } + if buffer.release().is_err() { + failed.set(true); + } + return Err(primary); + } + Ok(buffer) +} + +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +#[path = "gdn_state_mirror_gpu.rs"] +mod gpu_tests; diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror_gpu.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror_gpu.rs new file mode 100644 index 00000000..8851bf61 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror_gpu.rs @@ -0,0 +1,320 @@ +//! New device mirror against the actual uncached recurrence, not a model oracle. +#![cfg(all(target_os = "linux", target_arch = "x86_64"))] +use super::super::{GdnOwner, HISTORY_ELEMENTS, recur}; +use super::*; +use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId, TokenLayer}; +use leleka_cuda_driver::Driver; + +struct Inputs { + q: Vec, + k: Vec, + v: Vec, + gate: [f32; 48], + beta: [f32; 48], +} + +fn inputs(seed: usize) -> Inputs { + Inputs { + q: (0..2048) + .map(|i| ((i + seed * 3) % 17) as f32 / 128. - 0.0625) + .collect(), + k: (0..2048) + .map(|i| ((i * 3 + seed * 5) % 19) as f32 / 128. - 0.0703125) + .collect(), + v: (0..VALUES) + .map(|i| { + if seed == 2 { + if i % 2 == 0 { -0.0 } else { 0.0 } + } else { + ((i + seed * 7) % 23) as f32 / 64. - 0.171875 + } + }) + .collect(), + gate: std::array::from_fn(|i| -0.125 - ((i + seed) % 4) as f32 / 16.), + beta: std::array::from_fn(|i| if (i + seed) % 2 == 0 { 0.25 } else { 0.5 }), + } +} + +fn exact(left: &[f32], right: &[f32]) { + assert_eq!(left.len(), right.len()); + for (i, (left, right)) in left.iter().zip(right).enumerate() { + assert!(left.is_finite() && right.is_finite()); + assert_eq!(left.to_bits(), right.to_bits(), "word{i}"); + } +} + +fn pair<'ctx>( + context: &Context<'_>, + mirror: &mut GdnStateMirror<'ctx>, + prior: &GdnPrior, + seed: usize, +) -> MirrorNext<'ctx> { + let inputs = inputs(seed); + let initial = context.allocated_bytes(); + // Existing uncached CUDA producer is the reference. Its original input + // upload/release, arithmetic and finite readbacks remain unchanged. + let (expected_state, expected_readout) = recur( + context, + prior.values(), + &inputs.q, + &inputs.k, + &inputs.v, + &inputs.gate, + &inputs.beta, + ) + .unwrap(); + assert_eq!(context.allocated_bytes(), initial); + let source_bits: Vec = prior.values().iter().map(|v| v.to_bits()).collect(); + let (readout, next) = mirror + .compute( + prior, + &inputs.q, + &inputs.k, + &inputs.v, + &inputs.gate, + &inputs.beta, + ) + .unwrap(); + exact(&next.values, &expected_state); + exact(&readout, &expected_readout); + assert_eq!(context.allocated_bytes(), initial + MIRROR_BYTES); + assert_eq!( + prior + .values() + .iter() + .map(|v| v.to_bits()) + .collect::>(), + source_bits + ); + println!("GDN_MIRROR PAIR seed={seed} state_words=786432 readout_words=6144 exact=true"); + next +} + +fn identity(prior: &GdnPrior, seed: usize) -> TokenLayer { + TokenLayer::new( + TokenId::new(seed as u64, Dimension::new(248320).unwrap()).unwrap(), + Position::new(prior.next_position(), Dimension::new(262144).unwrap()).unwrap(), + prior.layer(), + ) +} + +#[test] +#[ignore = "root schedules one changed GDN mirror component proof"] +fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + // The actual implementation preserves the conservative 128MiB working + // reserve. This budget does not mean the fixture allocates 160MiB. + let context = device.create_context(160 * 1024 * 1024).unwrap(); + let binding = BindingIdentity::test_identity(); // Identity tag, never a pinned ModelBinding. + let owner = GdnOwner::new(); + let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); + let failed = Rc::new(Cell::new(false)); + let mut mirror = GdnStateMirror::new(binding.clone(), 0, &context, failed.clone()).unwrap(); + assert_eq!(context.allocated_bytes(), 3145728); + let mut prior = GdnPrior::zero(binding.clone(), &owner, layer).unwrap(); + let mut rollback = None; + for seed in 0..4 { + let next = pair(&context, &mut mirror, &prior, seed); + let candidate = mirror + .publish(next, identity(&prior, seed), prior.history().into()) + .unwrap(); + assert_eq!( + candidate.validate(&prior.clone(), identity(&prior, seed)), + Ok(()) + ); + if seed == 0 { + let rival = GdnPrior::zero(binding.clone(), &owner, layer).unwrap(); + assert!(!prior.same_state(&rival)); + assert_eq!( + candidate.validate(&rival, identity(&prior, seed)), + Err(Error::IdentityMismatch) + ); + } + prior = candidate.into_prior(); + if seed == 0 { + rollback = Some(prior.clone()); + } + assert_eq!(prior.next_position(), (seed + 1) as u64); + assert_eq!(context.allocated_bytes(), MIRROR_BYTES); + } + assert_eq!((mirror.hits, mirror.misses), (3, 1)); + let restored = rollback.unwrap(); + assert_eq!(restored.next_position(), 1); + let next = pair(&context, &mut mirror, &restored, 4); + let candidate = mirror + .publish(next, identity(&restored, 4), restored.history().into()) + .unwrap(); + assert_eq!((mirror.hits, mirror.misses), (3, 2)); + let accepted_restored = candidate.into_prior(); + assert_eq!(accepted_restored.next_position(), 2); + + let reset_owner = GdnOwner::new(); + let reset = GdnPrior::zero(binding.clone(), &reset_owner, layer).unwrap(); + let next = pair(&context, &mut mirror, &reset, 5); + assert_eq!((mirror.hits, mirror.misses), (3, 3)); + // Payload and exact source Rc are sealed into the actual candidate. A + // wrong position must reclaim it without installing a mirror key. + let wrong_identity = TokenLayer::new( + TokenId::new(5, Dimension::new(248320).unwrap()).unwrap(), + Position::new(1, Dimension::new(262144).unwrap()).unwrap(), + layer, + ); + assert_eq!( + mirror + .publish(next, wrong_identity, reset.history().into()) + .err(), + Some(Error::IdentityMismatch) + ); + assert_eq!(context.allocated_bytes(), MIRROR_BYTES); + assert!( + mirror + .key + .as_ref() + .is_some_and(|key| key.matches(&accepted_restored)) + ); + assert_eq!(reset.next_position(), 0); + assert!(reset.values().iter().all(|v| v.to_bits() == 0)); + assert_eq!(reset.history().len(), HISTORY_ELEMENTS); + + let ordinary = inputs(6); + let initial = context.allocated_bytes(); + let mut malformed = ordinary.q.clone(); + malformed[2047] = f32::from_bits(0x7fc00001); + assert_eq!( + mirror + .compute( + &reset, + &malformed, + &ordinary.k, + &ordinary.v, + &ordinary.gate, + &ordinary.beta + ) + .err(), + Some(Error::NonFinite) + ); + assert_eq!(context.allocated_bytes(), initial); + assert_eq!((mirror.hits, mirror.misses), (3, 3)); + let wrong_layer = GdnPrior::zero( + binding.clone(), + &owner, + LayerId::new(1, Dimension::new(48).unwrap()).unwrap(), + ) + .unwrap(); + assert_eq!( + mirror + .compute( + &wrong_layer, + &ordinary.q, + &ordinary.k, + &ordinary.v, + &ordinary.gate, + &ordinary.beta + ) + .err(), + Some(Error::IdentityMismatch) + ); + let wrong_binding = GdnPrior::zero(BindingIdentity::test_identity(), &owner, layer).unwrap(); + assert_eq!( + mirror + .compute( + &wrong_binding, + &ordinary.q, + &ordinary.k, + &ordinary.v, + &ordinary.gate, + &ordinary.beta + ) + .err(), + Some(Error::IdentityMismatch) + ); + assert_eq!(context.allocated_bytes(), initial); + assert!(!failed.get()); + + // Finite raw inputs can overflow the native recurrence. Unlike the early + // NaN refusal above, this reaches full D2H validation and candidate cleanup. + let mut preserved = vec![0; MIRROR_BYTES]; + mirror + .buffer + .as_ref() + .unwrap() + .copy_to(&mut preserved) + .unwrap(); + let mut overflow = inputs(6); + overflow.v.fill(f32::MAX); + overflow.beta.fill(f32::MAX); + assert_eq!( + mirror + .compute( + &accepted_restored, + &overflow.q, + &overflow.k, + &overflow.v, + &overflow.gate, + &overflow.beta + ) + .err(), + Some(Error::NonFinite) + ); + assert_eq!(context.allocated_bytes(), initial); + assert!( + mirror + .key + .as_ref() + .is_some_and(|key| key.matches(&accepted_restored)) + ); + let mut after = vec![0; MIRROR_BYTES]; + mirror.buffer.as_ref().unwrap().copy_to(&mut after).unwrap(); + assert_eq!(after, preserved); + assert!(!failed.get()); + assert_eq!((mirror.hits, mirror.misses), (4, 3)); + + // Real completed next is discarded on a downstream abort. This is a + // lifecycle check, not another independently paired numerical case. + let valid = inputs(7); + let (readout, next) = mirror + .compute( + &accepted_restored, + &valid.q, + &valid.k, + &valid.v, + &valid.gate, + &valid.beta, + ) + .unwrap(); + assert!( + readout + .iter() + .chain(next.values.iter()) + .all(|v| v.is_finite()) + ); + assert_eq!(context.allocated_bytes(), initial + MIRROR_BYTES); + mirror.discard(next).unwrap(); + assert_eq!(context.allocated_bytes(), initial); + assert!( + mirror + .key + .as_ref() + .is_some_and(|key| key.matches(&accepted_restored)) + ); + mirror.buffer.as_ref().unwrap().copy_to(&mut after).unwrap(); + assert_eq!(after, preserved); + assert!(!failed.get()); + assert_eq!((mirror.hits, mirror.misses), (5, 3)); + mirror.close().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + context.synchronize().unwrap(); + context.close().unwrap(); + // One byte below exact eager mirror + mandatory scratch reserve. + let small = device.create_context(137363455).unwrap(); + assert_eq!( + GdnStateMirror::new(binding, 0, &small, Rc::new(Cell::new(false))).err(), + Some(Error::InputAllocation) + ); + assert_eq!(small.allocated_bytes(), 0); + small.close().unwrap(); + println!( + "GDN_MIRROR COMPLETE primary_steps=4 rollback_reset_pairs=2 exact_words=4755456 preserved_mirror_words=1572864 hits=5 misses=3 refusals=6 discard=1 allocated=0" + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_activation_reuse_gpu.rs b/crates/leleka-runtime/src/qwen_forward/moe_activation_reuse_gpu.rs new file mode 100644 index 00000000..aa6d67e5 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_activation_reuse_gpu.rs @@ -0,0 +1,433 @@ +//! New retained Gate/Up lifecycle proof through actual projection/SwiGLU/Down. +#![cfg(all(target_os = "linux", target_arch = "x86_64"))] +use super::*; +use leleka_cuda_driver::Driver; +use std::cell::Cell; + +fn encoded(kind: MoeMatrixKind, rows: usize, columns: usize, variant: usize) -> Vec { + use MoeMatrixKind as K; + let (elements, bytes) = match kind { + K::Iq3Xxs => (256, 98), + K::Iq3S => (256, 110), + K::Iq2S => (256, 82), + K::RoutedIq4Xs | K::DenseIq4Xs => (256, 136), + K::Q4K => (256, 144), + K::Q5K => (256, 176), + K::Q6K => (256, 210), + K::RoutedIq4Nl => (32, 18), + K::Q8_0 => (32, 34), + _ => panic!("fixture has no other format"), + }; + let stride = columns / elements * bytes; + let mut values = vec![0; rows * stride]; + for (row, chunk) in values.chunks_exact_mut(stride).enumerate() { + for (block, chunk) in chunk.chunks_exact_mut(bytes).enumerate() { + for (i, byte) in chunk.iter_mut().enumerate() { + *byte = ((row * 17 + block * 29 + i * 37 + 11 + variant * 53) % 256) as u8; + } + if kind == K::Q6K { + chunk[208..210].copy_from_slice(&0x3c00u16.to_le_bytes()); + } else { + chunk[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + if matches!(kind, K::Q4K | K::Q5K) { + chunk[2..4].copy_from_slice(&0x3800u16.to_le_bytes()); + } + } + } + } + values +} + +fn exact(left: &[f32], right: &[f32]) { + assert_eq!(left.len(), right.len()); + for (i, (left, right)) in left.iter().zip(right).enumerate() { + assert!(left.is_finite() && right.is_finite()); + assert_eq!(left.to_bits(), right.to_bits(), "word{i}"); + } +} + +fn bounded_gate_up(kind: MoeMatrixKind, variant: usize) -> Vec { + let mut values = encoded(kind, FF, N, variant); + let block_bytes = match kind { + MoeMatrixKind::Iq3Xxs => 98, + MoeMatrixKind::Iq3S => 110, + MoeMatrixKind::Iq2S => 82, + MoeMatrixKind::RoutedIq4Xs | MoeMatrixKind::DenseIq4Xs => 136, + MoeMatrixKind::Q4K => 144, + MoeMatrixKind::Q5K => 176, + MoeMatrixKind::Q6K => 210, + _ => panic!("bounded fixture admits only Gate/Up formats"), + }; + for block in values.chunks_exact_mut(block_bytes) { + let scale_offset = if kind == MoeMatrixKind::Q6K { 208 } else { 0 }; + // Literal F16 2^-12; affine minima use 2^-13. Packed patterns stay + // unchanged. Together with |input|<=15/2048, source packed bounds + // conservatively give |Gate/Up|<20, |hidden|<=400, warp|sum|<=12800. + block[scale_offset..scale_offset + 2].copy_from_slice(&0x0c00u16.to_le_bytes()); + if matches!(kind, MoeMatrixKind::Q4K | MoeMatrixKind::Q5K) { + block[2..4].copy_from_slice(&0x0800u16.to_le_bytes()); + } + } + values +} + +fn down_projection( + context: &Context<'_>, + kind: MoeMatrixKind, + matrix: &DeviceBuffer<'_>, + hidden: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, +) -> std::result::Result<(), DriverError> { + let projection = match kind { + MoeMatrixKind::RoutedIq4Nl => ProjectionKind::Routed(RoutedFormat::IQ4_NL), + MoeMatrixKind::Q8_0 => ProjectionKind::Dense(DenseFormat::Q8_0), + _ => panic!("fixture admits only the original two Down formats"), + }; + context.project_q8_1( + matrix, + hidden, + output, + ProjectionSpec { + kind: projection, + rows: N, + columns: FF, + }, + ) +} + +fn raw<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> DeviceBuffer<'ctx> { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + upload_bytes(context, &bytes).unwrap() +} + +fn down( + context: &Context<'_>, + kind: MoeMatrixKind, + matrix: &DeviceBuffer<'_>, + hidden: &DeviceBuffer<'_>, +) -> Result> { + let mut output = context.allocate(N * 4).map_err(driver_error)?; + let result = down_projection(context, kind, matrix, hidden, &mut output) + .inspect_err(|error| eprintln!("MOE_RETAINED raw_down_error={error:?}")) + .map_err(driver_error) + .and_then(|()| download_f32(&output, N)); + let closed = output.release().map_err(driver_error); + let values = result?; + closed?; + Ok(values) +} + +fn compare_mlp( + context: &Context<'_>, + gate: DeviceBuffer<'_>, + up: DeviceBuffer<'_>, + down_kind: MoeMatrixKind, + down_matrix: &DeviceBuffer<'_>, +) { + // Genuine retained reference chain: completed finite readback, two uploads, + // original SwiGLU and same actual Down kernel. No host numerical oracle. + let gate_values = download_f32(&gate, FF).unwrap(); + let up_values = download_f32(&up, FF).unwrap(); + let old_gate = upload_f32(context, &gate_values).unwrap(); + let old_up = upload_f32(context, &up_values).unwrap(); + let mut old_hidden = context.allocate(FF * 4).unwrap(); + context + .moe_swiglu_f32(&old_gate, &old_up, &mut old_hidden) + .unwrap(); + let expected_hidden = download_f32(&old_hidden, FF).unwrap(); + for value in expected_hidden.iter() { + assert!( + value.abs() <= 400., + "fixture exceeds predeclared Q8 header domain" + ); + } + let expected = down(context, down_kind, down_matrix, &old_hidden).unwrap(); + old_hidden.release().unwrap(); + old_up.release().unwrap(); + old_gate.release().unwrap(); + let retained = context.allocated_bytes(); + let called = Cell::new(false); + let actual = finish_cached_mlp(context, gate, up, |hidden| { + called.set(true); + exact(&download_f32(hidden, FF)?, &expected_hidden); + down(context, down_kind, down_matrix, hidden) + }) + .unwrap(); + assert!(called.get()); + exact(&actual, &expected); + assert_eq!(context.allocated_bytes(), retained - 2 * FF * 4); +} + +fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bool, zero: bool) { + let input: Vec = (0..N) + .map(|i| { + if zero { + if i % 2 == 0 { -0.0 } else { 0.0 } + } else { + ((i % 31) as f32 - 15.) / 2048. + } + }) + .collect(); + let gate_bytes = bounded_gate_up(kind, 0); + let up_bytes = bounded_gate_up(kind, 1); + let down_kind = if routed { + MoeMatrixKind::RoutedIq4Nl + } else { + MoeMatrixKind::Q8_0 + }; + let down_bytes = encoded(down_kind, N, FF, 2); + let x = upload_f32(context, &input).unwrap(); + let gate_matrix = upload_bytes(context, &gate_bytes).unwrap(); + let up_matrix = upload_bytes(context, &up_bytes).unwrap(); + let down_matrix = upload_bytes(context, &down_bytes).unwrap(); + let gate = project_retained_gate_up(context, |out| { + launch_projection(context, kind, &gate_matrix, &x, out, FF, N) + }) + .unwrap(); + let up = project_retained_gate_up(context, |out| { + launch_projection(context, kind, &up_matrix, &x, out, FF, N) + }) + .unwrap(); + for buffer in [&gate, &up] { + for value in download_f32(buffer, FF).unwrap().iter() { + assert!( + value.abs() < 20., + "fixture exceeds predeclared Gate/Up bound" + ); + } + } + compare_mlp(context, gate, up, down_kind, &down_matrix); + exact(&download_f32(&x, N).unwrap(), &input); + for (matrix, bytes) in [ + (&gate_matrix, &gate_bytes), + (&up_matrix, &up_bytes), + (&down_matrix, &down_bytes), + ] { + let mut unchanged = vec![0; bytes.len()]; + matrix.copy_to(&mut unchanged).unwrap(); + assert_eq!(&unchanged, bytes); + } + down_matrix.release().unwrap(); + up_matrix.release().unwrap(); + gate_matrix.release().unwrap(); + x.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + println!("MOE_RETAINED PASS {kind:?} zero={zero} hidden640_down2560_bits=3200"); +} + +fn former_fixture_domain_refusal(context: &Context<'_>) { + // One new diagnostic of the actual prior failure, in the same scheduled + // run: original scale1/input/8 chain, preserving the raw driver error. + let input: Vec = (0..N).map(|i| ((i % 31) as f32 - 15.) / 8.).collect(); + let x = upload_f32(context, &input).unwrap(); + let gate_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 0)).unwrap(); + let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap(); + let down_matrix = + upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap(); + let gate = project_retained_gate_up(context, |output| { + launch_projection( + context, + MoeMatrixKind::Iq3Xxs, + &gate_matrix, + &x, + output, + FF, + N, + ) + }) + .unwrap(); + let up = project_retained_gate_up(context, |output| { + launch_projection( + context, + MoeMatrixKind::Iq3Xxs, + &up_matrix, + &x, + output, + FF, + N, + ) + }) + .unwrap(); + let mut hidden = context.allocate(FF * 4).unwrap(); + context.moe_swiglu_f32(&gate, &up, &mut hidden).unwrap(); + let values = download_f32(&hidden, FF).unwrap(); + let maximum = values + .iter() + .map(|value| value.abs()) + .fold(0.0f32, f32::max); + let maximum_sum = values + .chunks_exact(32) + .map(|warp| { + warp.iter() + .map(|value| f64::from(*value)) + .sum::() + .abs() + }) + .fold(0.0f64, f64::max); + let mut output = context.allocate(N * 4).unwrap(); + let sentinel = vec![0xa5; N * 4]; + output.copy_from(&sentinel).unwrap(); + let charged = context.allocated_bytes(); + let result = down_projection( + context, + MoeMatrixKind::RoutedIq4Nl, + &down_matrix, + &hidden, + &mut output, + ); + println!( + "MOE_RETAINED original_domain raw_down_error={result:?} hidden_abs_max={maximum} warp_sum_abs_max={maximum_sum}" + ); + assert_eq!(result, Err(DriverError::InvalidQ8Activation)); + assert_eq!(context.allocated_bytes(), charged); + let mut untouched = vec![0; sentinel.len()]; + output.copy_to(&mut untouched).unwrap(); + assert_eq!(untouched, sentinel); + output.release().unwrap(); + hidden.release().unwrap(); + up.release().unwrap(); + gate.release().unwrap(); + down_matrix.release().unwrap(); + up_matrix.release().unwrap(); + gate_matrix.release().unwrap(); + x.release().unwrap(); + context.synchronize().unwrap(); + assert_eq!(context.allocated_bytes(), 0); +} + +fn saturation_and_refusals(context: &Context<'_>) { + let down_bytes = encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 3); + let matrix = upload_bytes(context, &down_bytes).unwrap(); + let gate = upload_f32(context, &[-1000.; FF]).unwrap(); + let up = upload_f32(context, &[1.; FF]).unwrap(); + compare_mlp(context, gate, up, MoeMatrixKind::RoutedIq4Nl, &matrix); + matrix.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + for (gate_bad, bits) in [(true, 0x7fc00001u32), (false, 0x7f800000)] { + let mut gate_values = vec![0.25; FF]; + let mut up_values = vec![0.5; FF]; + if gate_bad { + gate_values[FF - 1] = f32::from_bits(bits); + } else { + up_values[FF - 1] = f32::from_bits(bits); + } + let called = Cell::new(false); + let result = finish_cached_mlp( + context, + raw(context, &gate_values), + raw(context, &up_values), + |_| { + called.set(true); + panic!("nonfinite hidden must not enter Down"); + }, + ); + assert_eq!(result.err(), Some(Error::NonFinite)); + assert!(!called.get()); + assert_eq!(context.allocated_bytes(), 0); + } + // Actual projection writes a late NaN, exercising finite admission before + // the newly retained projection owner can be published. + let mut malformed = encoded(MoeMatrixKind::Q6K, FF, N, 0); + let end = malformed.len(); + malformed[end - 2..].copy_from_slice(&0x7e01u16.to_le_bytes()); + let w = upload_bytes(context, &malformed).unwrap(); + let x = upload_f32(context, &[0.25; N]).unwrap(); + let initial = context.allocated_bytes(); + assert_eq!( + project_retained_gate_up(context, |out| launch_projection( + context, + MoeMatrixKind::Q6K, + &w, + &x, + out, + FF, + N + )) + .err(), + Some(Error::NonFinite) + ); + assert_eq!(context.allocated_bytes(), initial); + x.release().unwrap(); + w.release().unwrap(); + // Down shape refusal is genuine native admission, not a fabricated error. + let w = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 0)).unwrap(); + let mut wrong = context.allocate(N * 4 - 4).unwrap(); + let sentinel = vec![0xa5; N * 4 - 4]; + wrong.copy_from(&sentinel).unwrap(); + let initial = context.allocated_bytes(); + let result = finish_cached_mlp( + context, + raw(context, &[0.25; FF]), + raw(context, &[0.5; FF]), + |hidden| { + launch_projection( + context, + MoeMatrixKind::RoutedIq4Nl, + &w, + hidden, + &mut wrong, + N, + FF, + )?; + panic!("wrong Down output must refuse"); + }, + ); + assert_eq!(result.err(), Some(Error::InvalidDimension)); + assert_eq!(context.allocated_bytes(), initial); + let mut unchanged = vec![0; sentinel.len()]; + wrong.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, sentinel); + wrong.release().unwrap(); + w.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); +} + +#[test] +#[ignore = "root schedules one changed retained-MoE component proof"] +fn retained_gate_up_matches_legacy_chain_and_closes_failed_candidates() { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let context = device.create_context(16 * 1024 * 1024).unwrap(); + former_fixture_domain_refusal(&context); + for (kind, routed) in [ + (MoeMatrixKind::Iq3Xxs, true), + (MoeMatrixKind::Iq3S, true), + (MoeMatrixKind::Iq2S, true), + (MoeMatrixKind::RoutedIq4Xs, true), + (MoeMatrixKind::Q4K, false), + (MoeMatrixKind::Q5K, false), + (MoeMatrixKind::Q6K, false), + (MoeMatrixKind::DenseIq4Xs, false), + ] { + for zero in [false, true] { + format_case(&context, kind, routed, zero); + } + } + saturation_and_refusals(&context); + let small = device.create_context(2 * FF * 4).unwrap(); + assert_eq!( + finish_cached_mlp( + &small, + raw(&small, &[0.25; FF]), + raw(&small, &[0.5; FF]), + |_| panic!("budget must refuse before Down") + ) + .err(), + Some(Error::InputAllocation) + ); + assert_eq!(small.allocated_bytes(), 0); + small.close().unwrap(); + let small = device.create_context(FF * 4 - 1).unwrap(); + assert_eq!( + project_retained_gate_up(&small, |_| panic!("budget must refuse before projection")).err(), + Some(Error::InputAllocation) + ); + assert_eq!(small.allocated_bytes(), 0); + small.close().unwrap(); + context.synchronize().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + context.close().unwrap(); + println!( + "MOE_RETAINED COMPLETE paired_words=54400 finite_cases=17 original_refusal_cases=6 domain_diagnostic_refusals=1 allocated=0" + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_expert.rs b/crates/leleka-runtime/src/qwen_forward/moe_expert.rs index cc7246a6..bb23fd35 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_expert.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_expert.rs @@ -213,6 +213,47 @@ fn expert_mlp( mut cache: Option<&mut MoeWeightCache<'_>>, prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { + if let Some(cache) = cache.as_deref_mut() { + let gate = project_cached_gate_up( + context, + binding, + weights, + selection, + MoeMatrixRole::Gate, + activation, + cache, + prepared, + )?; + let up = match project_cached_gate_up( + context, + binding, + weights, + selection, + MoeMatrixRole::Up, + activation, + cache, + prepared, + ) { + Ok(up) => up, + Err(primary) => { + let _ = gate.release(); + return Err(primary); + } + }; + return finish_cached_mlp(context, gate, up, |hidden| { + project_matrix( + context, + binding, + weights, + selection, + MoeMatrixRole::Down, + hidden, + Some(cache), + None, + ) + }); + } + // Genuine uncached diagnostic: keep its original download/reupload chain. let gate = project_matrix( context, binding, @@ -262,6 +303,93 @@ fn expert_mlp( } } #[allow(clippy::too_many_arguments)] +fn project_cached_gate_up<'ctx>( + context: &'ctx Context<'_>, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + role: MoeMatrixRole, + activation: &DeviceBuffer<'_>, + cache: &mut MoeWeightCache<'_>, + prepared: Option<&RoutedGateUpQ8<'_>>, +) -> Result> { + let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?; + let kind = weights.kind(selection, role).map_err(binding_error)?; + if !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) || rows != FF || columns != N { + return Err(Error::InvalidDimension); + } + cache.validate(binding, context)?; + let matrix = cache.matrix(binding, weights, selection, role)?; + project_retained_gate_up(context, |output| { + if let Some(prepared) = prepared { + if !matches!(selection, MoeExpertSelection::Routed { .. }) { + return Err(Error::InvalidDimension); + } + let format = match kind { + MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS, + MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S, + MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S, + MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS, + _ => return Err(Error::Unsupported(Stage::MoeExpert)), + }; + context + .project_routed_gate_up_prepared(matrix, prepared, output, format) + .map_err(driver_error) + } else { + launch_projection(context, kind, matrix, activation, output, rows, columns) + } + }) +} +// Fixed 640-value projection lifecycle shared by the cached artifact path and +// its real-driver component fixture. Readback admission precedes the next op. +fn project_retained_gate_up<'ctx>( + context: &'ctx Context<'_>, + project: impl FnOnce(&mut DeviceBuffer<'ctx>) -> Result<()>, +) -> Result> { + let mut output = context.allocate(FF * 4).map_err(driver_error)?; + let result = project(&mut output).and_then(|()| download_f32(&output, FF).map(|_| ())); + match result { + Ok(()) => Ok(output), + Err(primary) => { + let _ = output.release(); + Err(primary) + } + } +} +fn finish_cached_mlp( + context: &Context<'_>, + gate: DeviceBuffer<'_>, + up: DeviceBuffer<'_>, + down: impl FnOnce(&DeviceBuffer<'_>) -> Result>, +) -> Result> { + let mut hidden = match context.allocate(FF * 4).map_err(driver_error) { + Ok(hidden) => hidden, + Err(primary) => { + let _ = gate.release(); + let _ = up.release(); + return Err(primary); + } + }; + let result = (|| { + // Original arithmetic, including valid saturated negative-gate zero. + context + .moe_swiglu_f32(&gate, &up, &mut hidden) + .map_err(driver_error)?; + download_f32(&hidden, FF)?; + down(&hidden) + })(); + // Attempt every owned release after the last use; primary work/readback + // failure wins, and any cleanup failure withholds a completed candidate. + let gate_close = gate.release().map_err(driver_error); + let up_close = up.release().map_err(driver_error); + let hidden_close = hidden.release().map_err(driver_error); + let values = result?; + gate_close?; + up_close?; + hidden_close?; + Ok(values) +} +#[allow(clippy::too_many_arguments)] fn project_matrix( context: &Context<'_>, binding: &ModelBinding, @@ -497,6 +625,9 @@ fn driver_error(error: DriverError) -> Error { } } #[cfg(test)] +#[path = "moe_activation_reuse_gpu.rs"] +mod moe_activation_reuse_gpu; +#[cfg(test)] mod tests { use super::*; #[test]