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 e558ba87..4b9a971f 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 @@ -1,7 +1,8 @@ //! Separate whole-expert resident GPU / owned native CPU miss producer. //! Only genuine completed rows reach the original ascending-slot combine. use super::*; -use crate::qwen_forward::cpu_expert_miss::runtime_error; +use crate::model_binding::qwen4exp_input::MoeWeightDescriptor; +use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error}; #[allow(clippy::too_many_arguments)] pub(super) fn project_adaptive_groups<'ctx>( @@ -21,6 +22,70 @@ pub(super) fn project_adaptive_groups<'ctx>( for row in rows { cache.observe_strata_adaptive_row(binding, &row.row().weights)?; } + let (residents, misses) = split_resident_misses(binding, rows, groups, cache)?; + // Actual outer wave directories coexist with owned jobs until join. + let wave_metadata = residents + .capacity() + .checked_add(misses.capacity()) + .and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>())) + .and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>())) + .ok_or(Error::Overflow)?; + let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?; + let mut gpu_done = false; + let cpu_owner = cache.cpu_miss_owner(binding)?; + let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let mut offset = 0usize; + while offset < misses.len() { + let end = miss_batch_end(rows, &misses, offset)?; + let batch = &misses[offset..end]; + offset = end; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let jobs = prepare_cpu_jobs(binding, rows, batch, &cpu, job_allowance)?; + // 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. + let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; + let gpu_result = if gpu_done { + Ok(()) + } else { + let done = + project_residents(context, binding, rows, &residents, cache, prepared, scope, origins, down, cancelled); + gpu_done = done.is_ok(); + done + }; + // Always drain actual CPU consumers, including GPU failure/cancellation. + // Preserve the primary GPU failure; no source allocation outlives join. + let completed = pending.join().map_err(runtime_error); + gpu_result?; + let completed = completed?; + if completed.len() != batch.len() { + return Err(Error::IdentityMismatch); + } + for (values, pairs) in completed.into_iter().zip(batch) { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?; + upload_completed_rows(scope, binding, &keys, pairs, &values, origins, down)?; + drop(values.into_values()); + } + } + if !gpu_done { + project_residents(context, binding, rows, &residents, cache, prepared, scope, origins, down, cancelled)?; + } + Ok(()) +} + +/// Resident groups run on the GPU; misses are cut into row-ordered batches of at most eight pairs. +fn split_resident_misses<'g>( + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &'g [Vec], + cache: &mut MoeWeightCache<'_>, +) -> Result<(Vec<&'g [Pair]>, Vec<&'g [Pair]>)> { let mut residents = Vec::new(); let mut misses = Vec::new(); residents.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; @@ -41,184 +106,201 @@ pub(super) fn project_adaptive_groups<'ctx>( } } } - // Actual outer wave directories coexist with owned jobs until join. - let wave_metadata = residents - .capacity() - .checked_add(misses.capacity()) - .and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>())) - .and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>())) - .ok_or(Error::Overflow)?; - let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?; - let mut gpu_done = false; - let cpu_owner = cache.cpu_miss_owner(binding)?; - let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let mut offset = 0usize; - while offset < misses.len() { - let mut end = offset; - let mut seen = [false; 512]; - while end < misses.len() && end - offset < 16 { - let first = misses[end][0]; - let expert = rows[first.row].row().route.experts()[first.slot].get() as usize; - if expert >= 512 { - return Err(Error::InvalidExpert); - } - if seen[expert] { - break; - } - seen[expert] = true; - end += 1; + Ok((residents, misses)) +} + +/// End of the next CPU batch: at most 16 miss groups with distinct experts. +fn miss_batch_end(rows: &[ChunkFfnRow], misses: &[&[Pair]], offset: usize) -> Result { + let mut end = offset; + let mut seen = [false; 512]; + while end < misses.len() && end - offset < 16 { + let first = misses[end][0]; + let expert = rows[first.row].row().route.experts()[first.slot].get() as usize; + if expert >= 512 { + return Err(Error::InvalidExpert); } - if end == offset { - return Err(Error::IdentityMismatch); + if seen[expert] { + break; } - let batch = &misses[offset..end]; - offset = end; + seen[expert] = true; + end += 1; + } + if end == offset { + return Err(Error::IdentityMismatch); + } + Ok(end) +} + +#[allow(clippy::too_many_arguments)] +fn project_residents<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + residents: &[&[Pair]], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, +) -> Result<()> { + for pairs in residents { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let mut jobs = Vec::new(); - jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; - let mut prepared_bytes = 0usize; - let preparation_metadata = jobs - .capacity() - .checked_mul(std::mem::size_of::()) + project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; + } + Ok(()) +} + +/// Prepare the owned CPU jobs of one batch under the 48MiB wave allowance. +fn prepare_cpu_jobs( + binding: &ModelBinding, + rows: &[ChunkFfnRow], + batch: &[&[Pair]], + cpu: &CpuMissWorkspace, + job_allowance: usize, +) -> Result> { + let mut jobs = Vec::new(); + jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; + let mut prepared_bytes = 0usize; + let preparation_metadata = + jobs.capacity().checked_mul(std::mem::size_of::()).ok_or(Error::Overflow)?; + for pairs in batch { + let job = prepare_cpu_job(binding, rows, pairs, cpu, prepared_bytes, preparation_metadata, job_allowance)?; + prepared_bytes = + prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?).ok_or(Error::InputAllocation)?; + if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { + return Err(Error::InputAllocation); + } + jobs.push(job); + } + Ok(jobs) +} + +fn prepare_cpu_job( + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pairs: &[Pair], + cpu: &CpuMissWorkspace, + prepared_bytes: usize, + preparation_metadata: usize, + job_allowance: usize, +) -> Result { + let first = pairs[0]; + let members = [(&rows[first.row].row().weights, first.slot)]; + let mut inputs = Vec::new(); + inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + for pair in pairs { + inputs.push(rows[pair.row].row().read.ready().mixed()); + } + binding.with_moe_routed_source(&members, binding_error, |source| { + // Final immutable native blob temporarily coexists with all + // three actual source role Boxes and the owned row inputs. + let raw_bytes = + [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold(0usize, |n, role| { + n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow) + })?; + let preparation_peak = raw_bytes + .checked_mul(2) + .and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows))) + .and_then(|n| n.checked_add(prepared_bytes)) + .and_then(|n| n.checked_add(preparation_metadata)) + .and_then(|n| { + inputs.capacity().checked_mul(std::mem::size_of::<&[f32]>()).and_then(|refs| n.checked_add(refs)) + }) + .and_then(|n| n.checked_add(std::mem::size_of::())) .ok_or(Error::Overflow)?; - for pairs in batch { - let first = pairs[0]; - let members = [(&rows[first.row].row().weights, first.slot)]; - let mut inputs = Vec::new(); - inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - for pair in *pairs { - inputs.push(rows[pair.row].row().read.ready().mixed()); - } - let job = binding.with_moe_routed_source(&members, binding_error, |source| { - // Final immutable native blob temporarily coexists with all - // three actual source role Boxes and the owned row inputs. - let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold( - 0usize, - |n, role| { - n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow) - }, - )?; - let preparation_peak = raw_bytes - .checked_mul(2) - .and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows))) - .and_then(|n| n.checked_add(prepared_bytes)) - .and_then(|n| n.checked_add(preparation_metadata)) - .and_then(|n| { - inputs - .capacity() - .checked_mul(std::mem::size_of::<&[f32]>()) - .and_then(|refs| n.checked_add(refs)) - }) - .and_then(|n| { - n.checked_add(std::mem::size_of::()) - }) - .ok_or(Error::Overflow)?; - if preparation_peak > job_allowance { - return Err(Error::InputAllocation); - } - let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; - // Owned immutable validated bytes detach before other actor GPU - // callbacks; no RefMut/source/Context crosses the CPU thread. - source.finish().map_err(binding_error)?; - Ok(job) - })?; - prepared_bytes = - prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?).ok_or(Error::InputAllocation)?; - if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { - return Err(Error::InputAllocation); - } - jobs.push(job); + if preparation_peak > job_allowance { + return Err(Error::InputAllocation); } - // 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. - let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; - let gpu_result = (|| { - if !gpu_done { - for pairs in &residents { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; - } - gpu_done = true; - } - Ok(()) - })(); - // Always drain actual CPU consumers, including GPU failure/cancellation. - // Preserve the primary GPU failure; no source allocation outlives join. - let completed = pending.join().map_err(runtime_error); - gpu_result?; - let completed = completed?; - if completed.len() != batch.len() { + let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; + // Owned immutable validated bytes detach before other actor GPU + // callbacks; no RefMut/source/Context crosses the CPU thread. + source.finish().map_err(binding_error)?; + Ok(job) + }) +} + +/// Validate one completed CPU batch member against its source descriptors and row origins. +#[allow(clippy::too_many_arguments)] +fn completed_keys<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pairs: &[Pair], + values: &CpuMissRows, + cache: &mut MoeWeightCache<'_>, + origins: &[Rc], + down: &[[Option>; K]], + actual: Option<&QwenChunkTxn<'_, '_>>, +) -> Result<[MoeWeightDescriptor; 3]> { + 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)?, + ]; + if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { return Err(Error::IdentityMismatch); } - for (values, pairs) in completed.into_iter().zip(batch) { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let first = pairs[0]; - let members = [(&rows[first.row].row().weights, first.slot)]; - let keys = 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)?, - ]; - if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { - return Err(Error::IdentityMismatch); - } - source.finish().map_err(binding_error)?; - cache.validate(binding, context)?; - for pair in *pairs { - if let Some(actual) = actual { - actual.validate_ffn_row( - actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), - &rows[pair.row], - )?; - } - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) - || origins[pair.row].identity != id - || down[pair.row][pair.slot].is_some() - { - return Err(Error::IdentityMismatch); - } - } - Ok(keys) - })?; - // Retain the genuine completed CPU owner until every actual upload - // and device Down finite check has completed. No host-only proof. - for (row_index, pair) in pairs.iter().enumerate() { - let output = scope.upload_cpu_completed_row( - binding, - &keys, - DownSelection::Routed(pair.slot), - &values, - row_index, - )?; - down[pair.row][pair.slot] = Some(ActualDown { - origin: Rc::clone(&origins[pair.row]), - selection: MoeExpertSelection::Routed { slot: pair.slot }, - output, - }); - } - drop(values.into_values()); + source.finish().map_err(binding_error)?; + cache.validate(binding, context)?; + for pair in pairs { + validate_completed_pair(binding, rows, pair, origins, down, actual)?; } + Ok(keys) + }) +} + +fn validate_completed_pair( + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pair: &Pair, + origins: &[Rc], + down: &[[Option>; K]], + actual: Option<&QwenChunkTxn<'_, '_>>, +) -> Result<()> { + if let Some(actual) = actual { + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; } - if !gpu_done { - for pairs in residents { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; - } + let row = rows[pair.row].row(); + let id = row.route.identity(); + row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; + if !origins[pair.row].binding.matches(&binding.identity()) + || origins[pair.row].identity != id + || down[pair.row][pair.slot].is_some() + { + return Err(Error::IdentityMismatch); + } + Ok(()) +} + +/// Retain the genuine completed CPU owner until every actual upload +/// and device Down finite check has completed. No host-only proof. +fn upload_completed_rows<'ctx>( + scope: &DownScope<'ctx>, + binding: &ModelBinding, + keys: &[MoeWeightDescriptor; 3], + pairs: &[Pair], + values: &CpuMissRows, + origins: &[Rc], + down: &mut [[Option>; K]], +) -> Result<()> { + for (row_index, pair) in pairs.iter().enumerate() { + let output = + scope.upload_cpu_completed_row(binding, keys, DownSelection::Routed(pair.slot), values, row_index)?; + down[pair.row][pair.slot] = Some(ActualDown { + origin: Rc::clone(&origins[pair.row]), + selection: MoeExpertSelection::Routed { slot: pair.slot }, + output, + }); } Ok(()) }