STRA-338 size: engine moe_group_adaptive: AdaptiveWave run/run_batch/finish_members, preparation peak helpers (project_adaptive_groups 73 -> <=30)
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
//! Separate whole-expert resident GPU / owned native CPU miss producer.
|
||||
//! Only genuine completed rows reach the original ascending-slot combine.
|
||||
use super::*;
|
||||
use crate::model_binding::qwen4exp_input::MoeWeightDescriptor;
|
||||
use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor};
|
||||
use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error};
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -23,38 +23,87 @@ pub(super) fn project_adaptive_groups<'ctx>(
|
||||
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 job_allowance = wave_job_allowance(residents.capacity(), misses.capacity())?;
|
||||
let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared };
|
||||
wave.run(cache, down, cancelled, actual, &residents, &misses, job_allowance)
|
||||
}
|
||||
|
||||
/// Actual outer wave directories coexist with owned jobs until join.
|
||||
fn wave_job_allowance(residents: usize, misses: usize) -> Result<usize> {
|
||||
let wave_metadata = residents
|
||||
.capacity()
|
||||
.checked_add(misses.capacity())
|
||||
.checked_add(misses)
|
||||
.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));
|
||||
(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<DownOrigin>],
|
||||
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<ActualDown<'ctx>>; 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;
|
||||
}
|
||||
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.
|
||||
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<ActualDown<'ctx>>; 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 = 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
|
||||
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.
|
||||
@@ -64,19 +113,63 @@ pub(super) fn project_adaptive_groups<'ctx>(
|
||||
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<ActualDown<'ctx>>; K]],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
actual: Option<&QwenChunkTxn<'_, '_>>,
|
||||
completed: Vec<CpuMissRows>,
|
||||
batch: &[&[Pair]],
|
||||
) -> Result<()> {
|
||||
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());
|
||||
self.finish_member(cache, down, actual, pairs, values)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
if !gpu_done {
|
||||
project_residents(context, binding, rows, &residents, cache, prepared, scope, origins, down, cancelled)?;
|
||||
|
||||
fn project_residents(
|
||||
&self,
|
||||
residents: &[&[Pair]],
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; 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<ActualDown<'ctx>>; 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(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resident groups run on the GPU; misses are cut into row-ordered batches of at most eight pairs.
|
||||
@@ -189,28 +282,12 @@ fn prepare_cpu_job(
|
||||
) -> Result<PreparedCpuMiss> {
|
||||
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 inputs = row_inputs(rows, pairs)?;
|
||||
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::<PreparedCpuMiss>()))
|
||||
.ok_or(Error::Overflow)?;
|
||||
let raw_bytes = source_raw_bytes(source)?;
|
||||
let preparation_peak = preparation_peak(raw_bytes, &inputs, prepared_bytes, preparation_metadata)?;
|
||||
if preparation_peak > job_allowance {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
@@ -222,6 +299,37 @@ fn prepare_cpu_job(
|
||||
})
|
||||
}
|
||||
|
||||
fn row_inputs<'r>(rows: &'r [ChunkFfnRow], pairs: &[Pair]) -> Result<Vec<&'r [f32]>> {
|
||||
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());
|
||||
}
|
||||
Ok(inputs)
|
||||
}
|
||||
|
||||
fn source_raw_bytes(source: &MoeRoutedSourceScope<'_, '_>) -> Result<usize> {
|
||||
[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)
|
||||
})
|
||||
}
|
||||
|
||||
fn preparation_peak(
|
||||
raw_bytes: usize,
|
||||
inputs: &Vec<&[f32]>,
|
||||
prepared_bytes: usize,
|
||||
preparation_metadata: usize,
|
||||
) -> Result<usize> {
|
||||
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::<PreparedCpuMiss>()))
|
||||
.ok_or(Error::Overflow)
|
||||
}
|
||||
|
||||
/// Validate one completed CPU batch member against its source descriptors and row origins.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn completed_keys<'ctx>(
|
||||
|
||||
Reference in New Issue
Block a user