diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs index 913fb6a2..a6719b9b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs @@ -299,6 +299,14 @@ fn prepare_cpu_job( }) } +pub(super) fn source_keys(source: &MoeRoutedSourceScope<'_, '_>) -> Result<[MoeWeightDescriptor; 3]> { + Ok([ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]) +} + fn row_inputs<'r>(rows: &'r [ChunkFfnRow], pairs: &[Pair]) -> Result> { let mut inputs = Vec::new(); inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; @@ -346,11 +354,7 @@ fn completed_keys<'ctx>( let first = pairs[0]; let members = [(&rows[first.row].row().weights, first.slot)]; binding.with_moe_routed_source(&members, binding_error, |source| { - let keys = [ - source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; + let keys = source_keys(source)?; if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs index b1029a4e..ebe19365 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs @@ -18,6 +18,4 @@ use project_inner_fn::project_inner; #[path = "moe_group_adaptive_packets/stage_gpu_wave_fn.rs"] mod stage_gpu_wave_fn; #[allow(unused_imports)] -use stage_gpu_wave_fn::consume_gpu_wave; -#[allow(unused_imports)] use stage_gpu_wave_fn::stage_gpu_wave; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs index d9ef1e5e..904f65d7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs @@ -48,18 +48,29 @@ impl<'g> PacketPlan<'g> { } let pairs = groups[expert].as_slice(); validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let first = pairs[0]; - let weights = &rows[first.row].row().weights; - if cache.strata_adaptive_resident(binding, weights, MoeExpertSelection::Routed { slot: first.slot })? { - self.residents.push(pairs); - } else { - self.distinct_misses.push(pairs); - } + self.classify_pairs(binding, rows, pairs, cache)?; } } Ok(()) } + fn classify_pairs( + &mut self, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pairs: &'g [Pair], + cache: &mut MoeWeightCache<'_>, + ) -> Result<()> { + let first = pairs[0]; + let weights = &rows[first.row].row().weights; + if cache.strata_adaptive_resident(binding, weights, MoeExpertSelection::Routed { slot: first.slot })? { + self.residents.push(pairs); + } else { + self.distinct_misses.push(pairs); + } + Ok(()) + } + pub(super) fn assign_misses( &mut self, context: &Context<'_>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_wave_fn.rs index 6709c72d..b8798e25 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_wave_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_wave_fn.rs @@ -1,15 +1,19 @@ //! GPU queue and CPU miss batches of one adaptive packet wave (STRA-338 size: extract-method only). -use super::super::adaptive::{miss_batch_end, prepare_cpu_jobs}; +use super::super::adaptive::{miss_batch_end, prepare_cpu_jobs, source_keys}; use super::packet_plan_fn::PacketPlan; #[allow(unused_imports)] use super::*; use crate::model_binding::qwen4exp_input::MoeWeightDescriptor; use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace}; -/// The GPU miss queue state: the shared miss list, the next miss to stage and the occupied ephemeral slots. +/// The GPU miss queue state: the shared miss list, the next miss to stage and the occupied ephemeral slots, plus the +/// resident groups and CPU miss batches that run beside it. pub(super) struct GpuWave<'a, 'g> { pub(super) misses: &'a [&'g [Pair]], + pub(super) residents: &'a [&'g [Pair]], + pub(super) cpu_misses: &'a [&'g [Pair]], + pub(super) job_allowance: usize, pub(super) next: usize, pub(super) slots: &'a mut [Option], pub(super) done: bool, @@ -37,6 +41,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { stage_gpu_wave(context, binding, rows, gpu.misses, cache, &mut gpu.next, gpu.slots, cancelled) } + /// Wait for and project every occupied ephemeral slot of the GPU queue. pub(super) fn consume( &self, gpu: &mut GpuWave<'_, '_>, @@ -45,48 +50,58 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { - let (context, binding, rows) = (self.context, self.binding, self.rows); - let (prepared, scope, origins) = (self.prepared, self.scope, self.origins); - consume_gpu_wave( - context, binding, rows, gpu.misses, cache, prepared, scope, origins, packets, gpu.slots, cancelled, actual, - ) + for (slot, directory) in gpu.slots.iter_mut().enumerate() { + let Some(index) = *directory else { + continue; + }; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let owner = cache.ephemeral_routed_owner(self.binding, self.context)?; + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, self.binding)?; + let pairs = gpu.misses.get(index).ok_or(Error::IdentityMismatch)?; + self.project_one(pairs, Some(slot), cache, packets, cancelled, actual)?; + *directory = None; + } + Ok(()) } pub(super) fn project_residents( &self, - residents: &[&[Pair]], + gpu: &GpuWave<'_, '_>, + cache: &mut MoeWeightCache<'_>, + packets: &mut [ActualSlotPacket<'ctx>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + ) -> Result<()> { + for pairs in gpu.residents { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.project_one(pairs, None, cache, packets, cancelled, actual)?; + } + Ok(()) + } + + fn project_one( + &self, + pairs: &[Pair], + slot: Option, cache: &mut MoeWeightCache<'_>, packets: &mut [ActualSlotPacket<'ctx>], cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { let (context, binding, rows) = (self.context, self.binding, self.rows); - for pairs in residents { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - resident_queue::project_group_packets( - context, - binding, - rows, - pairs, - cache, - self.prepared, - self.scope, - self.origins, - packets, - cancelled, - actual, - None, - )?; - } - Ok(()) + let (prepared, scope, origins) = (self.prepared, self.scope, self.origins); + resident_queue::project_group_packets( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, slot, + ) } /// Residents (once), then the staged GPU misses, then the next stage of the queue. pub(super) fn gpu_phase( &self, - residents: &[&[Pair]], gpu: &mut GpuWave<'_, '_>, cache: &mut MoeWeightCache<'_>, packets: &mut [ActualSlotPacket<'ctx>], @@ -94,7 +109,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { if !gpu.done { - self.project_residents(residents, cache, packets, cancelled, actual)?; + self.project_residents(gpu, cache, packets, cancelled, actual)?; gpu.done = true; } self.consume(gpu, cache, packets, cancelled, actual)?; @@ -104,7 +119,6 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { pub(super) fn finish_gpu( &self, - residents: &[&[Pair]], gpu: &mut GpuWave<'_, '_>, cache: &mut MoeWeightCache<'_>, packets: &mut [ActualSlotPacket<'ctx>], @@ -112,7 +126,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { if !gpu.done { - self.project_residents(residents, cache, packets, cancelled, actual)?; + self.project_residents(gpu, cache, packets, cancelled, actual)?; } while gpu.slots.iter().any(Option::is_some) { self.consume(gpu, cache, packets, cancelled, actual)?; @@ -121,40 +135,23 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { Ok(()) } - #[allow(clippy::too_many_arguments)] pub(super) fn run_misses( &self, - plan: &PacketPlan<'_>, gpu: &mut GpuWave<'_, '_>, cache: &mut MoeWeightCache<'_>, packets: &mut [ActualSlotPacket<'ctx>], cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, '_>, - job_allowance: usize, ) -> Result<()> { let cpu_owner = cache.cpu_miss_owner(self.binding)?; let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let misses = gpu.cpu_misses; let mut offset = 0usize; - while offset < plan.misses.len() { - let end = miss_batch_end(self.rows, &plan.misses, offset)?; - let batch = &plan.misses[offset..end]; + while offset < misses.len() { + let end = miss_batch_end(self.rows, misses, offset)?; + let batch = &misses[offset..end]; offset = end; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, &cpu, job_allowance)?; - self.run_batch( - &plan.residents, - gpu, - cache, - packets, - cancelled, - actual, - &mut cpu, - batch, - jobs, - job_allowance, - )?; + self.run_batch(gpu, cache, packets, cancelled, actual, &mut cpu, batch)?; } Ok(()) } @@ -162,11 +159,11 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { /// Start the prepared CPU jobs, overlap the GPU phase, drain the CPU side, then upload the completed rows. /// Model-lifetime stacks/native scratch were admitted before the pool. This request admits <=16 jobs and /// <=48MiB INCLUDING actual directory, preparation and start/join metadata/capacities. Callees measure their own - /// retained capacities against this remaining allowance before send. + /// retained capacities against this remaining allowance before send. Always drain actual CPU consumers, + /// including GPU failure/cancellation; preserve the primary GPU failure; no source allocation outlives join. #[allow(clippy::too_many_arguments)] pub(super) fn run_batch( &self, - residents: &[&[Pair]], gpu: &mut GpuWave<'_, '_>, cache: &mut MoeWeightCache<'_>, packets: &mut [ActualSlotPacket<'ctx>], @@ -174,13 +171,13 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { actual: &QwenChunkTxn<'_, '_>, cpu: &mut CpuMissWorkspace, batch: &[&[Pair]], - jobs: Vec, - job_allowance: usize, ) -> Result<()> { - let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; - let gpu_result = self.gpu_phase(residents, gpu, cache, packets, cancelled, actual); - // Always drain actual CPU consumers, including GPU failure/cancellation. - // Preserve the primary GPU failure; no source allocation outlives join. + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, gpu.job_allowance)?; + let pending = cpu.start(jobs, gpu.job_allowance).map_err(runtime_error)?; + let gpu_result = self.gpu_phase(gpu, cache, packets, cancelled, actual); let completed = pending.join().map_err(runtime_error); gpu_result?; let completed = completed?; @@ -226,11 +223,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> { let first = pairs[0]; let members = [(&rows[first.row].row().weights, first.slot)]; binding.with_moe_routed_source(&members, binding_error, |source| { - let keys = [ - source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; + let keys = source_keys(source)?; if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs index 5ebc98e8..467ee9dc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs @@ -19,10 +19,7 @@ pub(super) fn project_inner<'ctx>( cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { - cache.poll_strata_adaptive(binding, false)?; - for row in rows { - cache.observe_strata_adaptive_row(binding, &row.row().weights)?; - } + observe_adaptive(binding, rows, cache)?; let mut plan = PacketPlan::new(groups.len())?; plan.classify(binding, rows, groups, cache, origins, packets, actual)?; plan.assign_misses(context, binding, rows, cache, actual)?; @@ -31,11 +28,20 @@ pub(super) fn project_inner<'ctx>( let mut mapped_slots = [None; 16]; let slots: &mut [Option] = if slot_count == 2 { &mut legacy_slots } else { &mut mapped_slots[..slot_count] }; let wave = PacketWave { context, binding, rows, prepared, scope, origins }; - let mut gpu = GpuWave { misses: &plan.gpu_misses, next: 0, slots, done: false }; + let (misses, residents, cpu_misses) = (&plan.gpu_misses[..], &plan.residents[..], &plan.misses[..]); + let mut gpu = GpuWave { misses, residents, cpu_misses, job_allowance: 0, next: 0, slots, done: false }; wave.stage(&mut gpu, cache, cancelled)?; - let job_allowance = plan.job_allowance()?; - wave.run_misses(&plan, &mut gpu, cache, packets, cancelled, actual, job_allowance)?; - wave.finish_gpu(&plan.residents, &mut gpu, cache, packets, cancelled, actual) + gpu.job_allowance = plan.job_allowance()?; + wave.run_misses(&mut gpu, cache, packets, cancelled, actual)?; + wave.finish_gpu(&mut gpu, cache, packets, cancelled, actual) +} + +fn observe_adaptive(binding: &ModelBinding, rows: &[ChunkFfnRow], cache: &mut MoeWeightCache<'_>) -> Result<()> { + cache.poll_strata_adaptive(binding, false)?; + for row in rows { + cache.observe_strata_adaptive_row(binding, &row.row().weights)?; + } + Ok(()) } /// The actual slot count of the ephemeral routed owner: legacy two-slot copies or the mapped 8/16-slot factory. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs index 110fd9d0..3f7e7b31 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs @@ -34,45 +34,3 @@ pub(super) fn stage_gpu_wave<'ctx>( } Ok(()) } -#[allow(clippy::too_many_arguments)] -pub(super) fn consume_gpu_wave<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - groups: &[&[Pair]], - cache: &mut MoeWeightCache<'_>, - prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, - origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], - slots: &mut [Option], - cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, -) -> Result<()> { - for (slot, directory) in slots.iter_mut().enumerate() { - let Some(index) = *directory else { - continue; - }; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let owner = cache.ephemeral_routed_owner(binding, context)?; - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; - resident_queue::project_group_packets( - context, - binding, - rows, - groups.get(index).ok_or(Error::IdentityMismatch)?, - cache, - prepared, - scope, - origins, - packets, - cancelled, - actual, - Some(slot), - )?; - *directory = None; - } - Ok(()) -}