diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs index 1562d4c0..a8e30544 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs @@ -9,3 +9,5 @@ mod impl_sharedexpertworkspace_2; mod impl_sharedexpertworkspace_2_2; #[path = "impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs"] mod impl_sharedexpertworkspace_3; +#[path = "impl_sharedexpertworkspace/shared_phases.rs"] +mod shared_phases; diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs index 043938ba..aeb2b99d 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl SharedExpertWorkspace (2). #[allow(unused_imports)] +use super::shared_phases::SharedStaging; use super::*; impl<'ctx> SharedExpertWorkspace<'ctx> { @@ -16,146 +17,15 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let handles = self.handles()?; let inputs = self.inputs(activation, &weights, packed, handles)?; let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; - let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; - let mut route = staging(40)?; - for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { - out.copy_from_slice(&value.to_le_bytes()); - } - let mut status_staging = staging(48)?; - let mut scalar_staging = staging(4)?; - let mut final_staging = staging(10240)?; - let mut values = Vec::new(); - values.try_reserve_exact(2560).map_err(|_| Error::HostAllocation)?; - values.resize(2560, 0.0); - let mut commands = Vec::new(); - commands.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Guard(kernels.guard[0], 12, ffi::MmqResidentArguments::zero(handles[9], 12))); - let statuses = status_spans(handles[9])?; - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[0].index()], - [inputs[1], inputs[0], handles[0]], - handles[7], - statuses[0], - 640, - 2560, - )?; - append_finite(&mut commands, kernels.guard[1], handles[0], statuses[1], 640); - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[1].index()], - [inputs[2], inputs[0], handles[1]], - handles[7], - statuses[2], - 640, - 2560, - )?; - append_finite(&mut commands, kernels.guard[1], handles[1], statuses[3], 640); - self.append_qwen( - &mut commands, - kernels.qwen[0], - Operation::MoeSwiglu, - &[self.buffer(0)?, self.buffer(1)?, self.buffer(2)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[2], statuses[4], 640); - append_projection( - &mut commands, - kernels.down[weights.down_kind.index()], - [inputs[3], handles[2], handles[3]], - handles[8], - statuses[5], - 2560, - 640, - )?; - append_finite(&mut commands, kernels.guard[1], handles[3], statuses[6], 2560); - self.append_qwen( - &mut commands, - kernels.qwen[1], - Operation::MoeSharedScalar, - &[activation, weights.scalar, self.buffer(4)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[4], statuses[7], 1); - self.append_qwen( - &mut commands, - kernels.qwen[2], - Operation::MoeSharedScale, - &[self.buffer(3)?, self.buffer(4)?, self.buffer(5)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[5], statuses[8], 2560); - append_finite(&mut commands, kernels.guard[1], inputs[5], statuses[9], 25600); - append_finite(&mut commands, kernels.guard[1], handles[10], statuses[10], 10); - self.append_qwen( - &mut commands, - kernels.qwen[3], - Operation::MoeCombine, - &[packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[6], statuses[11], 2560); - // All exact shapes/ranges/aliases/assets and owned staging precede the first write. - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - self.context.poisoned.set(true); - return Err(error); - } - }; - let mut operation = self.context.driver.api.copy_from(handles[10], &route); - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(self.context); - } - // These are blocking cuMemcpyDtoH calls, in one final drain phase, not async DMA. - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[9], &mut status_staging); - } - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[4], &mut scalar_staging); - } - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[6], &mut final_staging); - } + self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let st = SharedStaging::new(route_weights)?; + let mut commands = self.shared_commands((activation, packed), &weights, (&handles, &inputs))?; + let guard = self.enter_for_drain()?; + let mut st = st; + let operation = self.drain_shared(&handles, &mut commands, &mut st); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - std::mem::forget((commands, route, status_staging, scalar_staging, final_staging, values)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); - } - combine(combine(operation, sync), pop)?; - let mut result = [0u32; 12]; - for (out, bytes) in result.iter_mut().zip(status_staging.as_chunks::<4>().0) { - *out = u32::from_le_bytes(*bytes); - } - if result.iter().enumerate().any(|(i, status)| { - let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; - status & !permitted != 0 - }) { - self.failed = true; - self.context.poisoned.set(true); - return Err(Error::InvalidDriverValue("shared-tail numeric witness")); - } - let scalar = f32::from_le_bytes(scalar_staging.as_chunks::<4>().0[0]); - let refusal = first_refusal(result, scalar); - for (value, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) { - *value = f32::from_le_bytes(*bytes); - } - self.generation = generation; - Ok(SharedTailCompletion { - workspace: self, - _weights: weights, - _activation: activation, - _packed: packed, - statuses: result, - scalar, - refusal, - values: values.into_boxed_slice(), - generation, - }) + let st = self.settle_shared([operation, sync, pop], (commands, st))?; + self.finish_shared(st, generation, (weights, activation, packed)) } } diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs new file mode 100644 index 00000000..96b93b95 --- /dev/null +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs @@ -0,0 +1,199 @@ +//! STRA-338 size: the phases of `SharedExpertWorkspace::compose`, extracted in call order. + +#[allow(unused_imports)] +use super::*; +use crate::CurrentGuard; + +/// Host buffers one compose stages through; leaked on an uncertain drain. +pub(super) struct SharedStaging { + route: Vec, + status: Vec, + scalar: Vec, + finals: Vec, + values: Vec, +} + +impl SharedStaging { + pub(super) fn new(route_weights: &[f32; 10]) -> Result { + let mut route = staging(40)?; + for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { + out.copy_from_slice(&value.to_le_bytes()); + } + let status = staging(48)?; + let scalar = staging(4)?; + let finals = staging(10240)?; + let mut values = Vec::new(); + values.try_reserve_exact(2560).map_err(|_| Error::HostAllocation)?; + values.resize(2560, 0.0); + Ok(Self { route, status, scalar, finals, values }) + } + + /// Decodes the twelve status words; a bit outside the permitted ones is a failed witness (`None`). + fn status_words(&self) -> Option<[u32; 12]> { + let mut result = [0u32; 12]; + for (out, bytes) in result.iter_mut().zip(self.status.as_chunks::<4>().0) { + *out = u32::from_le_bytes(*bytes); + } + let bad = result.iter().enumerate().any(|(i, status)| { + let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; + status & !permitted != 0 + }); + (!bad).then_some(result) + } +} + +impl<'ctx> SharedExpertWorkspace<'ctx> { + /// The launches of one compose: gate/up projections, SwiGLU, down, scalar gate, scale and combine, each guarded. + pub(super) fn shared_commands( + &self, + (activation, packed): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + ) -> Result> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Guard(kernels.guard[0], 12, ffi::MmqResidentArguments::zero(handles[9], 12))); + let statuses = status_spans(handles[9])?; + self.append_gate_up(&mut commands, weights, (handles, inputs), &statuses)?; + self.append_down_and_combine(&mut commands, (activation, packed), weights, (handles, inputs), &statuses)?; + Ok(commands) + } + + fn append_gate_up( + &self, + commands: &mut Vec, + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let gate = kernels.gu[weights.gu_kind[0].index()]; + append_projection(commands, gate, [inputs[1], inputs[0], handles[0]], handles[7], statuses[0], 640, 2560)?; + append_finite(commands, kernels.guard[1], handles[0], statuses[1], 640); + let up = kernels.gu[weights.gu_kind[1].index()]; + append_projection(commands, up, [inputs[2], inputs[0], handles[1]], handles[7], statuses[2], 640, 2560)?; + append_finite(commands, kernels.guard[1], handles[1], statuses[3], 640); + let swiglu = [self.buffer(0)?, self.buffer(1)?, self.buffer(2)?]; + self.append_qwen(commands, kernels.qwen[0], Operation::MoeSwiglu, &swiglu)?; + append_finite(commands, kernels.guard[1], handles[2], statuses[4], 640); + Ok(()) + } + + fn append_down_and_combine( + &self, + commands: &mut Vec, + (activation, packed): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let down = kernels.down[weights.down_kind.index()]; + append_projection(commands, down, [inputs[3], handles[2], handles[3]], handles[8], statuses[5], 2560, 640)?; + append_finite(commands, kernels.guard[1], handles[3], statuses[6], 2560); + let scalar = [activation, weights.scalar, self.buffer(4)?]; + self.append_qwen(commands, kernels.qwen[1], Operation::MoeSharedScalar, &scalar)?; + append_finite(commands, kernels.guard[1], handles[4], statuses[7], 1); + self.append_scale_and_combine(commands, packed, (handles, inputs), statuses) + } + + fn append_scale_and_combine( + &self, + commands: &mut Vec, + packed: &DeviceBuffer<'_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let scale = [self.buffer(3)?, self.buffer(4)?, self.buffer(5)?]; + self.append_qwen(commands, kernels.qwen[2], Operation::MoeSharedScale, &scale)?; + append_finite(commands, kernels.guard[1], handles[5], statuses[8], 2560); + append_finite(commands, kernels.guard[1], inputs[5], statuses[9], 25600); + append_finite(commands, kernels.guard[1], handles[10], statuses[10], 10); + let combine = [packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?]; + self.append_qwen(commands, kernels.qwen[3], Operation::MoeCombine, &combine)?; + append_finite(commands, kernels.guard[1], handles[6], statuses[11], 2560); + Ok(()) + } + + /// Enters the context for the drain; an enter failure fails the workspace. + pub(super) fn enter_for_drain(&mut self) -> Result> { + self.context.enter().inspect_err(|_| { + self.failed = true; + self.context.poisoned.set(true); + }) + } + + /// All exact shapes/ranges/aliases/assets and owned staging precede the first write. These are blocking + /// cuMemcpyDtoH calls, in one final drain phase, not async DMA. + pub(super) fn drain_shared( + &self, + handles: &[ffi::BufferHandle; 11], + commands: &mut [Command], + st: &mut SharedStaging, + ) -> Result<()> { + self.context.driver.api.copy_from(handles[10], &st.route)?; + for command in commands { + command.launch(self.context)?; + } + self.context.driver.api.copy_to(handles[9], &mut st.status)?; + self.context.driver.api.copy_to(handles[4], &mut st.scalar)?; + self.context.driver.api.copy_to(handles[6], &mut st.finals) + } + + /// Marks the workspace failed on any error; an uncertain drain leaks every host buffer. + pub(super) fn settle_shared( + &mut self, + [operation, sync, pop]: [Result<()>; 3], + (commands, st): (Vec, SharedStaging), + ) -> Result { + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget((commands, st)); + return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); + } + combine(combine(operation, sync), pop)?; + Ok(st) + } + + /// Validates the witness words and builds the completion from the drained staging. + pub(super) fn finish_shared<'lease>( + &'lease mut self, + mut st: SharedStaging, + generation: u64, + keep: (SharedExpertWeights<'lease, 'lease>, &'lease DeviceBuffer<'lease>, &'lease DeviceBuffer<'lease>), + ) -> Result> { + let Some(statuses) = st.status_words() else { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("shared-tail numeric witness")); + }; + let scalar = f32::from_le_bytes(st.scalar.as_chunks::<4>().0[0]); + for (value, bytes) in st.values.iter_mut().zip(st.finals.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + self.generation = generation; + Ok(SharedTailCompletion::assemble(self, keep, (statuses, scalar, st.values), generation)) + } +} + +impl<'lease, 'ctx> SharedTailCompletion<'lease, 'ctx> { + fn assemble( + workspace: &'lease mut SharedExpertWorkspace<'ctx>, + (_weights, _activation, _packed): ( + SharedExpertWeights<'lease, 'lease>, + &'lease DeviceBuffer<'lease>, + &'lease DeviceBuffer<'lease>, + ), + (statuses, scalar, values): ([u32; 12], f32, Vec), + generation: u64, + ) -> Self { + let refusal = first_refusal(statuses, scalar); + let values = values.into_boxed_slice(); + Self { workspace, _weights, _activation, _packed, statuses, scalar, refusal, values, generation } + } +}