From 995f636bc3994f37a5471bcafdcf6d7fac7053ec Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 14:44:28 +0100 Subject: [PATCH] STRA-338 size: engine moe_group_adaptive: AdaptiveWave in adaptive_wave_fn (file size); tighten baselines --- .../src/qwen_forward/moe_group_adaptive.rs | 137 +---------------- .../moe_group_adaptive/adaptive_wave_fn.rs | 139 ++++++++++++++++++ limits-baseline.json | 6 +- 3 files changed, 145 insertions(+), 137 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs 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 a6719b9b..8f7476a2 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,8 +1,11 @@ //! Separate whole-expert resident GPU / owned native CPU miss producer. //! Only genuine completed rows reach the original ascending-slot combine. use super::*; +#[path = "moe_group_adaptive/adaptive_wave_fn.rs"] +mod adaptive_wave_fn; use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor}; use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error}; +use adaptive_wave_fn::AdaptiveWave; #[allow(clippy::too_many_arguments)] pub(super) fn project_adaptive_groups<'ctx>( @@ -38,140 +41,6 @@ fn wave_job_allowance(residents: usize, misses: usize) -> Result { (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation) } -/// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool. -#[derive(Clone, Copy)] -struct AdaptiveWave<'a, 'ctx> { - context: &'ctx Context<'ctx>, - binding: &'a ModelBinding, - rows: &'a [ChunkFfnRow], - scope: &'a DownScope<'ctx>, - origins: &'a [Rc], - prepared: &'a [RoutedGateUpQ8<'a>], -} - -impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { - /// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch. - #[allow(clippy::too_many_arguments)] - fn run( - &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, - residents: &[&[Pair]], - misses: &[&[Pair]], - job_allowance: usize, - ) -> Result<()> { - let mut gpu_done = false; - let cpu_owner = cache.cpu_miss_owner(self.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(self.rows, misses, offset)?; - let batch = &misses[offset..end]; - offset = end; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let resident = if gpu_done { None } else { Some(residents) }; - self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?; - gpu_done = true; - } - if !gpu_done { - self.project_residents(residents, cache, down, cancelled)?; - } - Ok(()) - } - - /// Start the CPU jobs of one batch, run the resident GPU groups (first batch only) while they execute, 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. - #[allow(clippy::too_many_arguments)] - fn run_batch( - &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, - cpu: &mut CpuMissWorkspace, - batch: &[&[Pair]], - residents: Option<&[&[Pair]]>, - job_allowance: usize, - ) -> Result<()> { - let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?; - let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; - let gpu_result = match residents { - None => Ok(()), - Some(residents) => self.project_residents(residents, cache, down, cancelled), - }; - // 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); - } - self.finish_members(cache, down, cancelled, actual, completed, batch) - } - - fn finish_members( - &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, - completed: Vec, - batch: &[&[Pair]], - ) -> Result<()> { - for (values, pairs) in completed.into_iter().zip(batch) { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - self.finish_member(cache, down, actual, pairs, values)?; - } - Ok(()) - } - - fn project_residents( - &self, - residents: &[&[Pair]], - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - ) -> Result<()> { - let (context, binding, rows) = (self.context, self.binding, self.rows); - project_residents( - context, - binding, - rows, - residents, - cache, - self.prepared, - self.scope, - self.origins, - down, - cancelled, - ) - } - - fn finish_member( - &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - actual: Option<&QwenChunkTxn<'_, '_>>, - pairs: &[Pair], - values: CpuMissRows, - ) -> Result<()> { - let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins); - let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?; - upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?; - drop(values.into_values()); - 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, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs new file mode 100644 index 00000000..0ac5f825 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs @@ -0,0 +1,139 @@ +//! The adaptive wave: resident GPU groups beside owned CPU miss batches (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, runtime_error}; + +/// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool. +#[derive(Clone, Copy)] +pub(super) struct AdaptiveWave<'a, 'ctx> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) rows: &'a [ChunkFfnRow], + pub(super) scope: &'a DownScope<'ctx>, + pub(super) origins: &'a [Rc], + pub(super) prepared: &'a [RoutedGateUpQ8<'a>], +} + +impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { + /// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch. + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &self, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, + residents: &[&[Pair]], + misses: &[&[Pair]], + job_allowance: usize, + ) -> Result<()> { + let mut gpu_done = false; + let cpu_owner = cache.cpu_miss_owner(self.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(self.rows, misses, offset)?; + let batch = &misses[offset..end]; + offset = end; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let resident = if gpu_done { None } else { Some(residents) }; + self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?; + gpu_done = true; + } + if !gpu_done { + self.project_residents(residents, cache, down, cancelled)?; + } + Ok(()) + } + + /// Start the CPU jobs of one batch, run the resident GPU groups (first batch only) while they execute, 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. + #[allow(clippy::too_many_arguments)] + fn run_batch( + &self, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, + cpu: &mut CpuMissWorkspace, + batch: &[&[Pair]], + residents: Option<&[&[Pair]]>, + job_allowance: usize, + ) -> Result<()> { + let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?; + let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; + let gpu_result = match residents { + None => Ok(()), + Some(residents) => self.project_residents(residents, cache, down, cancelled), + }; + // 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); + } + self.finish_members(cache, down, cancelled, actual, completed, batch) + } + + fn finish_members( + &self, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, + completed: Vec, + batch: &[&[Pair]], + ) -> Result<()> { + for (values, pairs) in completed.into_iter().zip(batch) { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.finish_member(cache, down, actual, pairs, values)?; + } + Ok(()) + } + + fn project_residents( + &self, + residents: &[&[Pair]], + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + ) -> Result<()> { + let (context, binding, rows) = (self.context, self.binding, self.rows); + project_residents( + context, + binding, + rows, + residents, + cache, + self.prepared, + self.scope, + self.origins, + down, + cancelled, + ) + } + + fn finish_member( + &self, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + actual: Option<&QwenChunkTxn<'_, '_>>, + pairs: &[Pair], + values: CpuMissRows, + ) -> Result<()> { + let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins); + let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?; + upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?; + drop(values.into_values()); + Ok(()) + } +} diff --git a/limits-baseline.json b/limits-baseline.json index 99048a13..2bb1730a 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -53,10 +53,10 @@ "width": 1 }, "leleka-engine-qwen35-cuda": { - "fn_lines": 625, + "fn_lines": 613, "width": 755, - "complexity": 591, - "nesting": 22 + "complexity": 584, + "nesting": 21 }, "leleka-experimental-ref": { "fn_lines": 15,