diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs index d0697975..34b746b2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs @@ -80,6 +80,10 @@ struct Case<'c> { input_bytes: Vec, source: DeviceBuffer<'c>, history: Vec, + params: Params<'c>, +} +// The convolution, step and norm parameters, each as host values and a device copy. +struct Params<'c> { conv: Vec, conv_buffer: DeviceBuffer<'c>, dt: [f32; 48], @@ -89,6 +93,21 @@ struct Case<'c> { gamma: [f32; 128], gamma_buffer: DeviceBuffer<'c>, } +impl<'c> Params<'c> { + fn new(ctx: &'c Context<'c>) -> Self { + 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, a, gamma) = ([-2.; 48], [1.; 48], [1.; 128]); + let dt_buffer = upload(ctx, &dt).unwrap(); + let a_buffer = upload(ctx, &a).unwrap(); + let gamma_buffer = upload(ctx, &gamma).unwrap(); + Self { conv, conv_buffer, dt, a, dt_buffer, a_buffer, gamma, gamma_buffer } + } +} +// Signed zeros for the zero case, else the ramp. +fn zero_or_ramp(count: usize, zero: bool, ramp: impl Fn(usize) -> f32) -> Vec { + (0..count).map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ramp(i) }).collect() +} // The products of the pre-recurrence chain with the independent oracles they were compared to. struct Forward { qkv: Product, @@ -108,20 +127,11 @@ impl<'c> Case<'c> { let prior = GdnPrior::zero(binding.clone(), &owner, identity(0, 0).layer()).unwrap(); let mirror = GdnStateMirror::new(binding.clone(), 0, ctx, failed.clone()).unwrap(); let 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 = zero_or_ramp(2560, zero, |i| ((i % 17) as f32 - 8.) / 128.); 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, a, gamma) = ([-2.; 48], [1.; 48], [1.; 128]); - let dt_buffer = upload(ctx, &dt).unwrap(); - let a_buffer = upload(ctx, &a).unwrap(); - let gamma_buffer = upload(ctx, &gamma).unwrap(); + let history = zero_or_ramp(HISTORY_ELEMENTS, zero, |i| ((i % 13) as f32 - 6.) / 256.); + let params = Params::new(ctx); Self { ctx, foreign, @@ -136,23 +146,16 @@ impl<'c> Case<'c> { input_bytes, source, history, - conv, - conv_buffer, - dt, - a, - dt_buffer, - a_buffer, - gamma, - gamma_buffer, + params, } } fn forward(&mut self) -> Forward { let ctx = self.ctx; let (qkv, expected_qkv) = pair_projection(&mut self.chain, &self.source, &self.input, Role::Qkv, 0); - let expected_conv = convolve(ctx, &self.history, &expected_qkv, &self.conv, None).unwrap(); + let expected_conv = convolve(ctx, &self.history, &expected_qkv, &self.params.conv, None).unwrap(); let history_product = self.chain.upload(Role::History, &self.history).unwrap(); - let (next_history, h) = self.chain.convolve(&history_product, &qkv, &self.conv_buffer).unwrap(); + let (next_history, h) = self.chain.convolve(&history_product, &qkv, &self.params.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(); @@ -161,8 +164,9 @@ impl<'c> Case<'c> { let (alpha, expected_alpha) = pair_projection(&mut self.chain, &self.source, &self.input, Role::Alpha, 1); let (beta_raw, expected_beta_raw) = pair_projection(&mut self.chain, &self.source, &self.input, Role::BetaRaw, 2); - let expected_gates = gates(ctx, &expected_alpha, &expected_beta_raw, &self.dt, &self.a, None).unwrap(); - let (gate, beta) = self.chain.gates(&alpha, &beta_raw, &self.dt_buffer, &self.a_buffer).unwrap(); + let expected_gates = + gates(ctx, &expected_alpha, &expected_beta_raw, &self.params.dt, &self.params.a, None).unwrap(); + let (gate, beta) = self.chain.gates(&alpha, &beta_raw, &self.params.dt_buffer, &self.params.a_buffer).unwrap(); exact(gate.values(), &expected_gates.0); exact(beta.values(), &expected_gates.1); Forward { qkv, history_product, expected_conv, expected_qk, expected_gates } @@ -179,7 +183,7 @@ impl<'c> Case<'c> { ); assert_eq!(self.chain.validate(ctx, binding, identity(0, 1)), Err(Error::IdentityMismatch)); let charge = ctx.allocated_bytes(); - let mut bad_conv = self.conv.clone(); + let mut bad_conv = self.params.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!(self.chain.convolve(&fw.history_product, &fw.qkv, &bad).err(), Some(Error::NonFinite)); @@ -238,8 +242,9 @@ impl<'c> Case<'c> { fn normalized(&mut self, readout: &Product, expected_recur: &(Box<[f32]>, Box<[f32]>)) -> (Product, Box<[f32]>) { let (z, expected_z) = pair_projection(&mut self.chain, &self.source, &self.input, Role::Z, 3); - let expected_normalized = out_norm(self.ctx, &expected_recur.1, &expected_z, &self.gamma, 1e-6, None).unwrap(); - let normalized = self.chain.out_norm(readout, &z, &self.gamma_buffer, 1e-6).unwrap(); + let expected_normalized = + out_norm(self.ctx, &expected_recur.1, &expected_z, &self.params.gamma, 1e-6, None).unwrap(); + let normalized = self.chain.out_norm(readout, &z, &self.params.gamma_buffer, 1e-6).unwrap(); exact(normalized.values(), &expected_normalized); (normalized, expected_normalized) } @@ -277,7 +282,14 @@ impl<'c> Case<'c> { let mut unchanged_input = vec![0; self.input_bytes.len()]; self.source.copy_to(&mut unchanged_input).unwrap(); assert_eq!(unchanged_input, self.input_bytes); - release([self.source, self.conv_buffer, self.dt_buffer, self.a_buffer, self.gamma_buffer]).unwrap(); + release([ + self.source, + self.params.conv_buffer, + self.params.dt_buffer, + self.params.a_buffer, + self.params.gamma_buffer, + ]) + .unwrap(); self.chain.finish().unwrap(); self.mirror.close().unwrap(); assert_eq!(self.ctx.allocated_bytes(), 0); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs index f5605f5b..a63fe910 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs @@ -178,6 +178,14 @@ fn sticky_policy<'c>( assert!(failed.get()); } +// One byte below the scratch plus the mandatory reserve refuses the whole actor scratch. +fn small_budget_refusal(device: &leleka_cuda_driver::Device<'_>, binding: BindingIdentity) { + let small = device.create_context(128 * 1024 * 1024 + INPUT_BYTES - 1).unwrap(); + assert_eq!(GdnInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation)); + assert_eq!(small.allocated_bytes(), 0); + small.close().unwrap(); +} + #[test] #[ignore = "root schedules one changed GDN input scratch proof"] fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() { @@ -209,9 +217,6 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() context.close().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); - let small = device.create_context(128 * 1024 * 1024 + INPUT_BYTES - 1).unwrap(); - assert_eq!(GdnInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation)); - assert_eq!(small.allocated_bytes(), 0); - small.close().unwrap(); + small_budget_refusal(&device, binding); println!("GDN_INPUT COMPLETE exact_words=32960 finite_leases=2 guard_refusals=17 uploads=4 allocated=0"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs index 832df260..9a6706b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs @@ -62,7 +62,22 @@ struct Weights<'ctx> { gamma: DeviceBuffer<'ctx>, } -impl Weights<'_> { +impl<'ctx> Weights<'ctx> { + fn upload(ctx: &'ctx Context<'ctx>, host: &HostParams) -> Self { + let conv_host: Vec = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); + Self { + qkv: upload_bytes(ctx, &matrix(CHANNELS, 2560, 0)), + alpha: upload_bytes(ctx, &matrix(48, 2560, 1)), + beta: upload_bytes(ctx, &matrix(48, 2560, 2)), + z: upload_bytes(ctx, &matrix(VALUES, 2560, 3)), + out: upload_bytes(ctx, &matrix(2560, VALUES, 4)), + conv: upload(ctx, &conv_host).unwrap(), + conv_host, + dt: upload(ctx, &host.dt).unwrap(), + a: upload(ctx, &host.a).unwrap(), + gamma: upload(ctx, &host.gamma).unwrap(), + } + } fn release(self) { for buffer in [self.qkv, self.alpha, self.beta, self.z, self.out, self.conv, self.dt, self.a, self.gamma] { buffer.release().unwrap(); @@ -105,6 +120,14 @@ struct RowData<'ctx> { type Expected = (Box<[f32]>, Box<[f32]>, Box<[f32]>, Box<[f32]>); impl<'ctx> RowData<'ctx> { + fn release(self) { + let Self { source, state, next_state, bad, .. } = self; + if let Some(buffer) = bad { + buffer.release().unwrap(); + } + release([source, state, next_state]).unwrap(); + } + fn build( ctx: &'ctx Context<'ctx>, weights: &Weights<'ctx>, @@ -186,11 +209,7 @@ impl<'ctx> Rig<'ctx> { } chain.finish().unwrap(); // Every refusal and every success returns all row-local allocations. - let RowData { source, state, next_state, bad, .. } = data; - if let Some(buffer) = bad { - buffer.release().unwrap(); - } - release([source, state, next_state]).unwrap(); + data.release(); assert_eq!(self.ctx.allocated_bytes(), self.base_charge); assert!(!self.failed.get()); } @@ -202,12 +221,7 @@ impl<'ctx> Rig<'ctx> { let alpha = chain.project_device(&self.weights.alpha, GdnMatrixKind::Bf16, source, Role::Alpha).unwrap(); let beta_raw = chain.project_device(&self.weights.beta, GdnMatrixKind::Bf16, source, Role::BetaRaw).unwrap(); let z = chain.project_device(&self.weights.z, GdnMatrixKind::Bf16, source, Role::Z).unwrap(); - // The three device-only products refuse a wrong role and a roleless use. - assert_eq!(chain.operand_buffer(&alpha, Role::Z).err(), Some(Error::IdentityMismatch)); - assert_eq!( - chain.project_device(&self.weights.qkv, GdnMatrixKind::Bf16, source, Role::Qkv).err(), - Some(Error::IdentityMismatch) - ); + self.role_guards(chain, &alpha, source); let conv_buffer = data.bad.as_ref().unwrap_or(&self.weights.conv); chain.run_row_queue( &mut self.queue, @@ -228,6 +242,15 @@ impl<'ctx> Rig<'ctx> { ) } + // The three device-only products refuse a wrong role and a roleless use. + fn role_guards(&self, chain: &mut Chain<'ctx>, alpha: &DeviceOperand, source: &DeviceBuffer<'ctx>) { + assert_eq!(chain.operand_buffer(alpha, Role::Z).err(), Some(Error::IdentityMismatch)); + assert_eq!( + chain.project_device(&self.weights.qkv, GdnMatrixKind::Bf16, source, Role::Qkv).err(), + Some(Error::IdentityMismatch) + ); + } + fn compare_row( &self, chain: &mut Chain<'ctx>, @@ -297,19 +320,7 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { let binding = BindingIdentity::test_identity(); // Identity tag only, never a ModelBinding. let failed = Rc::new(Cell::new(false)); let host = HostParams { dt: [-2.; 48], a: [1.; 48], gamma: [1.; 128] }; - let conv_host: Vec = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); - let weights = Weights { - qkv: upload_bytes(&ctx, &matrix(CHANNELS, 2560, 0)), - alpha: upload_bytes(&ctx, &matrix(48, 2560, 1)), - beta: upload_bytes(&ctx, &matrix(48, 2560, 2)), - z: upload_bytes(&ctx, &matrix(VALUES, 2560, 3)), - out: upload_bytes(&ctx, &matrix(2560, VALUES, 4)), - conv: upload(&ctx, &conv_host).unwrap(), - conv_host, - dt: upload(&ctx, &host.dt).unwrap(), - a: upload(&ctx, &host.a).unwrap(), - gamma: upload(&ctx, &host.gamma).unwrap(), - }; + let weights = Weights::upload(&ctx, &host); let scratch = Rc::new(QkScratch::new(binding.clone(), &ctx, failed.clone()).unwrap()); let queue = ctx.gdn_row_queue().unwrap(); let base_charge = ctx.allocated_bytes(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs index aefe5cd8..2866bf73 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs @@ -191,7 +191,12 @@ impl<'c> Run<'c> { assert_eq!(after, preserved); assert!(!self.failed.get()); assert_eq!((self.mirror.hits, self.mirror.misses), (4, 3)); + self.discard_lifecycle(accepted_restored, initial, &preserved); + } + // A real completed next is discarded on a downstream abort: its buffer is freed, the mirror image is untouched. + fn discard_lifecycle(&mut self, accepted_restored: &GdnPrior, initial: usize, preserved: &[u8]) { + let mut after = vec![0; MIRROR_BYTES]; let valid = inputs(7); let (readout, next) = self.mirror.compute(accepted_restored, &valid.q, &valid.k, &valid.v, &valid.gate, &valid.beta).unwrap(); @@ -207,6 +212,14 @@ impl<'c> Run<'c> { } } +// One byte below exact eager mirror + mandatory scratch reserve. +fn small_budget_refusal(device: &leleka_cuda_driver::Device<'_>, binding: BindingIdentity) { + 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(); +} + #[test] #[ignore = "root schedules one changed GDN mirror component proof"] fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { @@ -230,11 +243,7 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { 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(); + small_budget_refusal(&device, binding); 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/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs index 3f175ac8..74381711 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs @@ -3,6 +3,362 @@ use super::*; use leleka_cuda_driver::Driver; +#[derive(Default)] +struct Tally { + words: usize, + differences: usize, + guards: usize, +} + +type Weights<'m, 'c> = &'m [DeviceBuffer<'c>; 4]; + +// The contexts and tags every stage of the proof uses. +struct Stage<'c> { + context: &'c Context<'c>, + foreign: &'c Context<'c>, + binding: &'c BindingIdentity, + failed: &'c Rc>, +} + +impl<'c> Stage<'c> { + fn weights<'m>(matrices: &'m [DeviceBuffer<'c>]) -> Result> { + matrices.try_into().map_err(|_| Error::InvalidDimension) + } + fn read_cached(&self, lease: &GrScratch<'c>, weights: Weights<'_, 'c>) -> Result { + read_cached_cuda( + self.context, + 1e-6, + true, + lease, + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], + ) + } + + // The fixed matrices: gamma, then the three BF16 weights. + fn upload_matrices(&self, matrices: &mut Vec>) -> Result<()> { + matrices.push(upload_f32(self.context, &vec![1.0; 10240])?); + for (count, seed) in [(3276800, 0), (3276800, 1), (40960, 2)] { + let values: Vec = (0..count).map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }).collect(); + matrices.push(upload_bf16(self.context, &values)?); + } + Ok(()) + } + + // One pattern: poison every retained byte, run the cached read and injection, compare them with fresh ones. + fn pattern_round( + &self, + cell: &RefCell>, + matrices: &[DeviceBuffer<'c>], + (pattern, charged): (usize, usize), + tally: &mut Tally, + ) -> Result<()> { + let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + lease.write(self.binding, self.context, &streams(pattern))?; + let weights = Self::weights(matrices)?; + let expected = fresh_read(self.context, lease.buffer(self.context)?, weights)?; + let block = block(pattern); + let expected_injected = + fresh_inject(self.context, lease.buffer(self.context)?, &block, &coefficients(&expected)?)?; + // Poison every retained byte BEFORE candidate, proving all + // six fixed outputs overwrite rather than reuse old results. + poison_all(&lease)?; + let actual = self.read_cached(&lease, weights)?; + self.compare_cached(&lease, (&expected, actual), (&block, &expected_injected), tally)?; + if cell.try_borrow_mut().is_ok() || self.context.allocated_bytes() != charged { + tally.differences += 1; + } + tally.guards += 1; + // No finish/publication: dropping the genuine lease is abort. + drop(lease); + Ok(()) + } + + // The six fixed outputs, the mixed values, the injection coefficients and the cached injection, bit for bit. + fn compare_cached( + &self, + lease: &GrScratch<'c>, + (expected, actual): (&[Vec], ReadCandidate), + (block, expected_injected): (&[f32], &[f32]), + tally: &mut Tally, + ) -> Result<()> { + let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); + compare_outputs(&outputs, expected, tally)?; + let mixed: Vec = actual.mixed.iter().flat_map(|v| v.to_le_bytes()).collect(); + if mixed != expected[5] { + tally.differences += 1; + } + let injected: Vec = + actual.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); + tally.differences += injected.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); + tally.words += 4; + let injected = inject_cached_cuda(self.context, lease, block, &actual.inject.ok_or(Error::InvalidDimension)?)?; + tally.differences += + injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + tally.words += injected.len(); + Ok(()) + } + + // A rival tag or a foreign context is refused, and a held output lease refuses the cached read. + fn identity_refusals( + &self, + lease: &mut GrScratch<'c>, + matrices: &[DeviceBuffer<'c>], + tally: &mut Tally, + ) -> Result<()> { + for (owner, ctx) in [(&BindingIdentity::test_identity(), self.context), (self.binding, self.foreign)] { + if lease.write(owner, ctx, &streams(1)) != Err(Error::IdentityMismatch) { + tally.differences += 1; + } + tally.guards += 1; + } + let weights = Self::weights(matrices)?; + let held = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); + if self.read_cached(lease, weights).err() != Some(Error::IdentityMismatch) { + tally.differences += 1; + } + tally.guards += 1; + drop(held); + Ok(()) + } + + // A late NaN in the gamma weights is refused and leaves the shared failure flag clear. + fn nonfinite_gamma( + &self, + lease: &GrScratch<'c>, + matrices: &mut [DeviceBuffer<'c>], + tally: &mut Tally, + ) -> Result<()> { + let mut gamma = vec![1.0f32; 10240]; + gamma[10239] = f32::NAN; + matrices[0].copy_from(&gamma.iter().flat_map(|v| v.to_le_bytes()).collect::>()).map_err(driver_error)?; + let weights = Self::weights(matrices)?; + if self.read_cached(lease, weights).err() != Some(Error::NonFinite) || self.failed.get() { + tally.differences += 1; + } + tally.guards += 1; + Ok(()) + } + + // After restoring gamma the same lease overwrites everything and recovers exactly. + fn recovery( + &self, + lease: &mut GrScratch<'c>, + matrices: &mut [DeviceBuffer<'c>], + (before, tally): (usize, &mut Tally), + ) -> Result<(Vec>, Vec)> { + matrices[0].copy_from(&1.0f32.to_le_bytes().repeat(10240)).map_err(driver_error)?; + let weights = Self::weights(matrices)?; + lease.write(self.binding, self.context, &streams(3))?; + let expected = fresh_read(self.context, lease.buffer(self.context)?, weights)?; + let block = block(3); + let expected_injected = + fresh_inject(self.context, lease.buffer(self.context)?, &block, &coefficients(&expected)?)?; + let recovered = self.read_cached(lease, weights)?; + self.compare_recovered(lease, (&expected, recovered), (&block, &expected_injected), tally)?; + if self.context.allocated_bytes() != before { + tally.differences += 1; + } + tally.guards += 1; + Ok((expected, block)) + } + + fn compare_recovered( + &self, + lease: &GrScratch<'c>, + (expected, recovered): (&[Vec], ReadCandidate), + (block, expected_injected): (&[f32], &[f32]), + tally: &mut Tally, + ) -> Result<()> { + let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); + compare_outputs(&outputs, expected, tally)?; + let injection: Vec = + recovered.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); + tally.differences += injection.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); + tally.words += 4; + drop(outputs); + let actual_injected = + inject_cached_cuda(self.context, lease, block, &recovered.inject.ok_or(Error::InvalidDimension)?)?; + tally.differences += + actual_injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + tally.words += actual_injected.len(); + Ok(()) + } + + // Held read-inject and injection leases refuse their users; a short or non-finite block is refused untouched. + fn lease_refusals( + &self, + lease: &mut GrScratch<'c>, + weights: Weights<'_, 'c>, + (expected, block): (&[Vec], &[f32]), + tally: &mut Tally, + ) -> Result<()> { + let held = lease.read_inject.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); + if self.read_cached(lease, weights).err() != Some(Error::IdentityMismatch) { + tally.differences += 1; + } + tally.guards += 1; + drop(held); + let held = lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); + if inject_cached_cuda(self.context, lease, block, &coefficients(expected)?).err() + != Some(Error::IdentityMismatch) + { + tally.differences += 1; + } + tally.guards += 1; + drop(held); + let before_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; + if inject_cached_cuda(self.context, lease, &block[..2559], &coefficients(expected)?).err() + != Some(Error::InvalidDimension) + { + tally.differences += 1; + } + tally.guards += 1; + let mut invalid = block.to_vec(); + invalid[2559] = f32::NAN; + if inject_cached_cuda(self.context, lease, &invalid, &coefficients(expected)?).err() != Some(Error::NonFinite) + || self.failed.get() + { + tally.differences += 1; + } + tally.guards += 1; + let after_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; + tally.differences += + before_refusal.iter().zip(after_refusal.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + Ok(()) + } + + // The retained-handoff replacement refuses a foreign context, a short block, a non-finite block and a + // non-finite output, each leaving the actor input untouched. + fn replace_refusals(&self, lease: &mut GrScratch<'c>, tally: &mut Tally) -> Result<()> { + let sentinel = download_f32(lease.buffer(self.context)?, 10240)?; + let input = streams(1); + let block = self::block(1); + let coefficients = [0.5, -0.25, 0.0, 1.0]; + for (ctx, current, expected) in [ + (self.foreign, &block[..], Error::IdentityMismatch), + (self.context, &block[..2559], Error::InvalidDimension), + ] { + if retained_handoff::inject_replace_residual(lease, ctx, &input, current, &coefficients).err() + != Some(expected) + { + tally.differences += 1; + } + tally.guards += 1; + } + let mut invalid = block.clone(); + invalid[2559] = f32::NAN; + if retained_handoff::inject_replace_residual(lease, self.context, &input, &invalid, &coefficients).err() + != Some(Error::NonFinite) + { + tally.differences += 1; + } + tally.guards += 1; + let after = download_f32(lease.buffer(self.context)?, 10240)?; + tally.differences += sentinel.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + tally.words += 10240; + // Valid finite inputs producing a genuinely nonfinite output must + // refuse BEFORE the residual swap; the current input remains. + let overflow = vec![f32::MAX; 2560]; + if retained_handoff::inject_replace_residual(lease, self.context, &input, &overflow, &[20.0; 4]).err() + != Some(Error::NonFinite) + || self.failed.get() + { + tally.differences += 1; + } + let after = download_f32(lease.buffer(self.context)?, 10240)?; + tally.differences += input.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + tally.words += 10240; + tally.guards += 1; + Ok(()) + } + + fn handoff_check( + &self, + lease: &mut GrScratch<'c>, + weights: Weights<'_, 'c>, + pattern: usize, + tally: &mut Tally, + ) -> Result<()> { + let (checked, different) = check_handoff(lease, self.context, self.binding, weights, pattern)?; + tally.words += checked; + tally.differences += different; + Ok(()) + } + + // The nominal stages after the patterns: refusals, recovery, the handoff rounds and the replacement refusals. + fn after_patterns( + &self, + cell: &RefCell>, + matrices: &mut [DeviceBuffer<'c>], + tally: &mut Tally, + ) -> Result<()> { + let mut lease = cell.borrow_mut(); + let before = self.context.allocated_bytes(); + let (expected, block) = self.refusal_phase(&mut lease, matrices, before, tally)?; + let weights = Self::weights(matrices)?; + self.lease_refusals(&mut lease, weights, (&expected, &block), tally)?; + for pattern in [0, 1, 1, 2] { + self.handoff_check(&mut lease, weights, pattern, tally)?; + if self.context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { + tally.differences += 1; + } + tally.guards += 1; + } + self.replace_refusals(&mut lease, tally)?; + // Abort exposes no readiness capability. Next actual call fully + // overwrites the failed candidate and all FFN read outputs. + drop(lease); + let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + self.handoff_check(&mut lease, weights, 3, tally)?; + if self.context.allocated_bytes() != before || self.failed.get() { + tally.differences += 1; + } + tally.guards += 1; + drop(lease); + Ok(()) + } + + fn refusal_phase( + &self, + lease: &mut GrScratch<'c>, + matrices: &mut [DeviceBuffer<'c>], + before: usize, + tally: &mut Tally, + ) -> Result<(Vec>, Vec)> { + self.identity_refusals(lease, matrices, tally)?; + self.nonfinite_gamma(lease, matrices, tally)?; + self.recovery(lease, matrices, (before, tally)) + } +} + +// The proof proper: the scratch and the matrices are owned by the caller so they are released even on failure. +fn run_proof<'c>( + stage: &Stage<'c>, + scratch: &mut Option>>, + matrices: &mut Vec>, +) -> Result<(usize, usize, usize)> { + *scratch = Some(RefCell::new(GrScratch::new_identity(stage.binding.clone(), stage.context, stage.failed.clone())?)); + stage.upload_matrices(matrices)?; + let cell = scratch.as_ref().ok_or(Error::CudaExecution)?; + let charged = stage.context.allocated_bytes(); + let mut tally = Tally::default(); + for pattern in [0, 1, 1, 2] { + stage.pattern_round(cell, matrices, (pattern, charged), &mut tally)?; + } + stage.after_patterns(cell, matrices, &mut tally)?; + Ok((tally.words, tally.differences, tally.guards)) +} + +fn compare_outputs(outputs: &[DeviceBuffer<'_>; 6], expected: &[Vec], tally: &mut Tally) -> Result<()> { + for (buffer, expected) in outputs.iter().zip(expected) { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + tally.differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); + tally.words += bytes.len() / 4; + } + Ok(()) +} + #[test] #[ignore = "Root-only changed persistent GR outputs, no model/old-suite replay"] fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { @@ -15,254 +371,8 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { let failed = Rc::new(Cell::new(false)); let mut scratch = None; let mut matrices = Vec::new(); - let operation: Result<(usize, usize, usize)> = (|| { - scratch = Some(RefCell::new(GrScratch::new_identity(binding.clone(), &context, failed.clone())?)); - matrices.push(upload_f32(&context, &vec![1.0; 10240])?); - for (count, seed) in [(3276800, 0), (3276800, 1), (40960, 2)] { - let values: Vec = (0..count).map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }).collect(); - matrices.push(upload_bf16(&context, &values)?); - } - let cell = scratch.as_ref().ok_or(Error::CudaExecution)?; - let charged = context.allocated_bytes(); - let mut differences = 0; - let mut words = 0; - let mut guards = 0; - for pattern in [0, 1, 1, 2] { - let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - lease.write(&binding, &context, &streams(pattern))?; - let weights: &[DeviceBuffer<'_>; 4] = - matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; - let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; - let block = block(pattern); - let expected_injected = fresh_inject(&context, lease.buffer(&context)?, &block, &coefficients(&expected)?)?; - // Poison every retained byte BEFORE candidate, proving all - // six fixed outputs overwrite rather than reuse old results. - for buffer in lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { - buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; - } - lease - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .copy_from(&f32::NAN.to_le_bytes().repeat(4)) - .map_err(driver_error)?; - for buffer in lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { - buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; - } - let actual = read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], - )?; - let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); - for (buffer, expected) in outputs.iter().zip(&expected) { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); - words += bytes.len() / 4; - } - let mixed: Vec = actual.mixed.iter().flat_map(|v| v.to_le_bytes()).collect(); - if mixed != expected[5] { - differences += 1; - } - let injected: Vec = - actual.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); - differences += injected.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); - words += 4; - let injected = - inject_cached_cuda(&context, &lease, &block, &actual.inject.ok_or(Error::InvalidDimension)?)?; - differences += - injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - words += injected.len(); - if cell.try_borrow_mut().is_ok() || context.allocated_bytes() != charged { - differences += 1; - } - guards += 1; - drop(outputs); - // No finish/publication: dropping the genuine lease is abort. - drop(lease); - } - let mut lease = cell.borrow_mut(); - let before = context.allocated_bytes(); - for (owner, ctx) in [(&BindingIdentity::test_identity(), &context), (&binding, &foreign)] { - if lease.write(owner, ctx, &streams(1)) != Err(Error::IdentityMismatch) { - differences += 1; - } - guards += 1; - } - let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; - let held = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], - ) - .err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let mut gamma = vec![1.0f32; 10240]; - gamma[10239] = f32::NAN; - matrices[0].copy_from(&gamma.iter().flat_map(|v| v.to_le_bytes()).collect::>()).map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], - ) - .err() - != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - guards += 1; - matrices[0].copy_from(&1.0f32.to_le_bytes().repeat(10240)).map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; - lease.write(&binding, &context, &streams(3))?; - let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; - let block = block(3); - let expected_injected = fresh_inject(&context, lease.buffer(&context)?, &block, &coefficients(&expected)?)?; - let recovered = read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], - )?; - let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); - for (buffer, expected) in outputs.iter().zip(&expected) { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); - words += bytes.len() / 4; - } - let injection: Vec = - recovered.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); - differences += injection.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); - words += 4; - drop(outputs); - let actual_injected = - inject_cached_cuda(&context, &lease, &block, &recovered.inject.ok_or(Error::InvalidDimension)?)?; - differences += - actual_injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - words += actual_injected.len(); - if context.allocated_bytes() != before { - differences += 1; - } - guards += 1; - let held = lease.read_inject.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], - ) - .err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let held = lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); - if inject_cached_cuda(&context, &lease, &block, &coefficients(&expected)?).err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let before_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; - if inject_cached_cuda(&context, &lease, &block[..2559], &coefficients(&expected)?).err() - != Some(Error::InvalidDimension) - { - differences += 1; - } - guards += 1; - let mut invalid = block.clone(); - invalid[2559] = f32::NAN; - if inject_cached_cuda(&context, &lease, &invalid, &coefficients(&expected)?).err() != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - guards += 1; - let after_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; - differences += - before_refusal.iter().zip(after_refusal.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - for pattern in [0, 1, 1, 2] { - let (checked, different) = check_handoff(&mut lease, &context, &binding, weights, pattern)?; - words += checked; - differences += different; - if context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { - differences += 1; - } - guards += 1; - } - let sentinel = download_f32(lease.buffer(&context)?, 10240)?; - let input = streams(1); - let block = self::block(1); - let coefficients = [0.5, -0.25, 0.0, 1.0]; - for (ctx, current, expected) in - [(&foreign, &block[..], Error::IdentityMismatch), (&context, &block[..2559], Error::InvalidDimension)] - { - if retained_handoff::inject_replace_residual(&mut lease, ctx, &input, current, &coefficients).err() - != Some(expected) - { - differences += 1; - } - guards += 1; - } - let mut invalid = block.clone(); - invalid[2559] = f32::NAN; - if retained_handoff::inject_replace_residual(&mut lease, &context, &input, &invalid, &coefficients).err() - != Some(Error::NonFinite) - { - differences += 1; - } - guards += 1; - let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += sentinel.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - words += 10240; - // Valid finite inputs producing a genuinely nonfinite output must - // refuse BEFORE the residual swap; the current input remains. - let overflow = vec![f32::MAX; 2560]; - if retained_handoff::inject_replace_residual(&mut lease, &context, &input, &overflow, &[20.0; 4]).err() - != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += input.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - words += 10240; - guards += 1; - // Abort exposes no readiness capability. Next actual call fully - // overwrites the failed candidate and all FFN read outputs. - drop(lease); - let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let (checked, different) = check_handoff(&mut lease, &context, &binding, weights, 3)?; - words += checked; - differences += different; - if context.allocated_bytes() != before || failed.get() { - differences += 1; - } - guards += 1; - drop(lease); - Ok((words, differences, guards)) - })(); + let stage = Stage { context: &context, foreign: &foreign, binding: &binding, failed: &failed }; + let operation = run_proof(&stage, &mut scratch, &mut matrices); let mut cleanup = Ok(()); for buffer in matrices.into_iter().rev() { let result = buffer.release().map_err(driver_error); @@ -291,7 +401,8 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { assert_eq!(differences, 0); assert_eq!(guards, 22); eprintln!( - "GR_OUTPUT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true full_overwrite=true" + "GR_OUTPUT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true \ + full_overwrite=true" ); } @@ -305,6 +416,8 @@ use fresh_read_fn::fresh_inject; #[allow(unused_imports)] use fresh_read_fn::fresh_read; #[allow(unused_imports)] +use fresh_read_fn::poison_all; +#[allow(unused_imports)] use fresh_read_fn::streams; mod check_handoff_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs index 2fbdb1b8..f993c48f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs @@ -13,32 +13,11 @@ pub(super) fn check_handoff<'ctx>( let input = streams(pattern); let block = block(pattern); let coefficients = [0.5, -0.25, 0.0, 1.0]; - scratch.write(binding, context, &input)?; - // Original fresh allocation/kernel/readback plus canonical host H2D - // FIRST. The following fresh FFN trace cannot come from the candidate. - let reference = fresh_inject(context, scratch.buffer(context)?, &block, &coefficients)?; - scratch.write(binding, context, &reference)?; - let reference_ffn = fresh_read(context, scratch.buffer(context)?, weights)?; - for buffer in scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { - buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; - } - scratch - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .copy_from(&f32::NAN.to_le_bytes().repeat(4)) - .map_err(driver_error)?; - for buffer in scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { - buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; - } + let (reference, reference_ffn) = + handoff_reference(scratch, context, binding, (&input, &block, &coefficients), weights)?; + poison_all(scratch)?; let actual = retained_handoff::inject_replace_residual(scratch, context, &input, &block, &coefficients)?; - let resident = download_f32(scratch.buffer(context)?, 10240)?; - let previous = download_f32(&scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; - let mut differences = 0; - for (left, right) in [(&actual[..], &reference[..]), (&resident[..], &reference[..]), (&previous[..], &input[..])] { - differences += left.iter().zip(right).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); - } + let mut differences = residual_differences(scratch, context, (&actual, &reference, &input))?; // No host residual upload: the actual swapped producer feeds FFN. let ffn = read_cached_cuda( context, @@ -47,8 +26,45 @@ pub(super) fn check_handoff<'ctx>( scratch, [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], )?; + differences += ffn_differences(scratch, ffn, &reference_ffn)?; + Ok((3 * 10240 + GR_OUTPUT_DEVICE_BYTES / 4 + 4, differences)) +} + +// Original fresh allocation/kernel/readback plus canonical host H2D FIRST. The following fresh FFN trace cannot +// come from the candidate. Returns the reference residual and the reference FFN trace. +fn handoff_reference<'ctx>( + scratch: &mut GrScratch<'ctx>, + context: &'ctx Context<'ctx>, + binding: &BindingIdentity, + (input, block, coefficients): (&[f32], &[f32], &[f32; 4]), + weights: &[DeviceBuffer<'_>; 4], +) -> Result<(Box<[f32]>, Vec>)> { + scratch.write(binding, context, input)?; + let reference = fresh_inject(context, scratch.buffer(context)?, block, coefficients)?; + scratch.write(binding, context, &reference)?; + let reference_ffn = fresh_read(context, scratch.buffer(context)?, weights)?; + Ok((reference, reference_ffn)) +} + +// The swapped residual, the resident residual and the previous input against their references. +fn residual_differences( + scratch: &GrScratch<'_>, + context: &Context<'_>, + (actual, reference, input): (&[f32], &[f32], &[f32]), +) -> Result { + let resident = download_f32(scratch.buffer(context)?, 10240)?; + let previous = download_f32(&scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; + let mut differences = 0; + for (left, right) in [(actual, reference), (&resident[..], reference), (&previous[..], input)] { + differences += left.iter().zip(right).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + } + Ok(differences) +} + +fn ffn_differences(scratch: &GrScratch<'_>, ffn: ReadCandidate, reference_ffn: &[Vec]) -> Result { + let mut differences = 0; let outputs = scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); - for (buffer, expected) in outputs.iter().zip(&reference_ffn) { + for (buffer, expected) in outputs.iter().zip(reference_ffn) { let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes).map_err(driver_error)?; differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); @@ -58,5 +74,5 @@ pub(super) fn check_handoff<'ctx>( if ffn.mixed.iter().flat_map(|v| v.to_le_bytes()).collect::>() != reference_ffn[5] { differences += 1; } - Ok((3 * 10240 + GR_OUTPUT_DEVICE_BYTES / 4 + 4, differences)) + Ok(differences) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs index 0ee0a779..f4c724a2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs @@ -11,51 +11,82 @@ pub(super) fn fresh_read( // Exact compiled289 per-read allocation boundary FIRST, same queued // kernels and fixed finite guard, never candidate-derived arithmetic. let mut owned = Vec::new(); - let operation: Result>> = (|| { - for bytes in GR_OUTPUT_BYTES.into_iter().chain([16]) { - owned.push(context.allocate(bytes).map_err(driver_error)?); - } - let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() else { - return Err(Error::InvalidDimension); - }; - let mask = context - .gr_read_chain_queued( - residual, - &weights[0], - &weights[1], - &weights[2], - 1e-6, - xn, - down, - activated, - gates, - products, - mixed, - ) - .map_err(driver_error)?; - if mask != 0 { - return Err(Error::NonFinite); - } - context.gr_inject_projection_bf16_f32(&weights[3], xn, injection).map_err(driver_error)?; - owned - .iter() - .map(|buffer| { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - Ok(bytes) - }) - .collect::>>() - })(); + let operation = fresh_read_launch(context, residual, weights, &mut owned); + let cleanup = release_reverse(owned); + let value = operation?; + cleanup?; + Ok(value) +} + +// Release in reverse order of creation, keeping the first failure. +fn release_reverse(buffers: Vec>) -> Result<()> { let mut cleanup = Ok(()); - for buffer in owned.into_iter().rev() { + for buffer in buffers.into_iter().rev() { let result = buffer.release().map_err(driver_error); if cleanup.is_ok() { cleanup = result; } } - let value = operation?; - cleanup?; - Ok(value) + cleanup +} + +fn fresh_read_launch<'c>( + context: &'c Context<'_>, + residual: &DeviceBuffer<'_>, + weights: &[DeviceBuffer<'_>; 4], + owned: &mut Vec>, +) -> Result>> { + for bytes in GR_OUTPUT_BYTES.into_iter().chain([16]) { + owned.push(context.allocate(bytes).map_err(driver_error)?); + } + let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() else { + return Err(Error::InvalidDimension); + }; + let mask = context + .gr_read_chain_queued( + residual, + &weights[0], + &weights[1], + &weights[2], + 1e-6, + xn, + down, + activated, + gates, + products, + mixed, + ) + .map_err(driver_error)?; + if mask != 0 { + return Err(Error::NonFinite); + } + context.gr_inject_projection_bf16_f32(&weights[3], xn, injection).map_err(driver_error)?; + owned + .iter() + .map(|buffer| { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + Ok(bytes) + }) + .collect::>>() +} + +// Every retained byte of the actor scratch is set to NaN, so a later overwrite is provable. +pub(super) fn poison_all(scratch: &GrScratch<'_>) -> Result<()> { + for buffer in scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; + } + scratch + .read_inject + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .copy_from(&f32::NAN.to_le_bytes().repeat(4)) + .map_err(driver_error)?; + for buffer in scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; + } + Ok(()) } pub(super) fn fresh_inject( @@ -76,13 +107,7 @@ pub(super) fn fresh_inject( context.gr_inject_residual_f32(residual, block, coefficients, candidate).map_err(driver_error)?; download_f32(candidate, 10240) })(); - let mut cleanup = Ok(()); - for buffer in owned.into_iter().rev() { - let result = buffer.release().map_err(driver_error); - if cleanup.is_ok() { - cleanup = result; - } - } + let cleanup = release_reverse(owned); let value = operation?; cleanup?; Ok(value)