diff --git a/crates/native-cpu-expert/src/impl_cpupool.rs b/crates/native-cpu-expert/src/impl_cpupool.rs index 69fe1767..a497e1ca 100644 --- a/crates/native-cpu-expert/src/impl_cpupool.rs +++ b/crates/native-cpu-expert/src/impl_cpupool.rs @@ -1,8 +1,84 @@ -//! Moved out of the parent module by STRA-338: impl CpuPool, impl PendingBatch, impl Drop_for_PendingBatch, impl Drop_for_CpuPool. +//! Moved out of the parent module by STRA-338: CpuPool, PendingBatch and their Drop impls. #[allow(unused_imports)] use super::*; +/// The coordinator thread: creates the native pool, reports its worker count (or the error) to `startup`, then serves +/// batches until the command channel closes. +fn run_coordinator( + workers: i32, + receive: mpsc::Receiver>, + send_result: mpsc::SyncSender>>, + startup: mpsc::SyncSender>, +) { + // No pointer/Context/Binding/source scope is captured from the actor. + let native = match ffi::NativePool::new(workers) { + Ok(pool) => pool, + Err(error) => { + let _ = startup.send(Err(error)); + return; + } + }; + if startup.send(native.workers()).is_err() { + return; + } + serve_batches(native, &receive, &send_result); +} + +/// Computes every received batch and sends it back, until the actor closes the channel, drops the result channel, or a +/// native failure closes the coordinator for good. +fn serve_batches( + mut native: ffi::NativePool, + receive: &mpsc::Receiver>, + send_result: &mpsc::SyncSender>>, +) { + while let Ok(mut jobs) = receive.recv() { + let result = native.compute_batch(&mut jobs); + if matches!(result, Err(Error::NativeFailure | Error::Allocation)) { + // A caught native exception might leave completion uncertain. + // Keep every job owner live until the original pool's stop + // and join completes, then close this coordinator forever. + drop(native); + drop(jobs); + let _ = send_result.send(result.map(|()| Vec::new())); + return; + } + let result = result.map(|()| jobs); + if send_result.send(result).is_err() { + break; + } + } + // NativePool is destroyed here; original destructor joins all workers. +} + +/// The result vector of a batch of `jobs` once the jobs are admitted: 1..=MAX_JOBS jobs in a vector of at most that +/// capacity, within `allowance` and the batch ceiling. `Shape`, `BudgetExceeded` or `Allocation` otherwise. +fn admit_batch(jobs: &Vec, allowance: usize) -> Result> { + if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { + return Err(Error::Shape); + } + if allowance > MAX_BATCH_BYTES { + return Err(Error::BudgetExceeded); + } + let mut results = Vec::new(); + results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + if batch_charge(jobs, &results)? > allowance { + return Err(Error::BudgetExceeded); + } + Ok(results) +} + +/// The bytes a batch is charged: the metadata of the job and result vectors plus the bytes every job owns. +fn batch_charge(jobs: &Vec, results: &Vec) -> Result { + let results_bytes = results.capacity().checked_mul(std::mem::size_of::()); + let metadata = jobs + .capacity() + .checked_mul(std::mem::size_of::()) + .and_then(|n| results_bytes.and_then(|m| n.checked_add(m))) + .ok_or(Error::BudgetExceeded)?; + jobs.iter().try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded)) +} + impl CpuPool { pub fn new(workers: i32) -> Result { let (command, receive) = mpsc::sync_channel::>(1); @@ -11,36 +87,7 @@ impl CpuPool { let worker = thread::Builder::new() .name("leleka-cpu-miss".into()) .stack_size(2 * 1024 * 1024) - .spawn(move || { - // No pointer/Context/Binding/source scope is captured from the actor. - let mut native = match ffi::NativePool::new(workers) { - Ok(pool) => pool, - Err(error) => { - let _ = startup.send(Err(error)); - return; - } - }; - if startup.send(native.workers()).is_err() { - return; - } - while let Ok(mut jobs) = receive.recv() { - let result = native.compute_batch(&mut jobs); - if matches!(result, Err(Error::NativeFailure | Error::Allocation)) { - // A caught native exception might leave completion uncertain. - // Keep every job owner live until the original pool's stop - // and join completes, then close this coordinator forever. - drop(native); - drop(jobs); - let _ = send_result.send(result.map(|()| Vec::new())); - return; - } - let result = result.map(|()| jobs); - if send_result.send(result).is_err() { - break; - } - } - // NativePool is destroyed here; original destructor joins all workers. - }) + .spawn(move || run_coordinator(workers, receive, send_result, startup)) .map_err(|_| Error::Allocation)?; match initialized.recv().unwrap_or(Err(Error::NativeFailure)) { Ok(workers) => Ok(Self { @@ -66,27 +113,7 @@ impl CpuPool { if self.failed || self.in_flight { return Err(Error::Closed); } - if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { - return Err(Error::Shape); - } - if allowance > MAX_BATCH_BYTES { - return Err(Error::BudgetExceeded); - } - let mut results = Vec::new(); - results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; - let metadata = jobs - .capacity() - .checked_mul(std::mem::size_of::()) - .and_then(|n| { - results.capacity().checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m)) - }) - .ok_or(Error::BudgetExceeded)?; - let charged = jobs - .iter() - .try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded))?; - if charged > allowance { - return Err(Error::BudgetExceeded); - } + let results = admit_batch(&jobs, allowance)?; if self.command.as_ref().ok_or(Error::Closed)?.send(jobs).is_err() { self.failed = true; return Err(Error::Closed); diff --git a/crates/native-cpu-expert/src/impl_gateupformat.rs b/crates/native-cpu-expert/src/impl_gateupformat.rs index a45a1cde..bff6b439 100644 --- a/crates/native-cpu-expert/src/impl_gateupformat.rs +++ b/crates/native-cpu-expert/src/impl_gateupformat.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl GateUpFormat, impl DownFormat, impl PreparedJob, impl DirectCpuPool, impl Drop_for_DirectCpuPool, impl CompletedJob. +//! Moved out of the parent module by STRA-338: the format tables, PreparedJob, DirectCpuPool and CompletedJob. #[allow(unused_imports)] use super::*; @@ -41,6 +41,58 @@ impl DownFormat { } } } +/// `NonFinite` when any block of the three role matrices starts with an FP16 header that is Inf or NaN. +/// +/// Every admitted family has one FP16 header at each original block start. Integer multipliers are bounded; this is a +/// guard, never a source proof. +fn validate_headers(roles: [(&[u8], usize); 3]) -> Result<()> { + for (bytes, block) in roles { + for at in (0..bytes.len()).step_by(block) { + if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 { + return Err(Error::NonFinite); + } + } + } + Ok(()) +} + +/// The complete native G|U|D owner: the three role matrices copied one after the other into one fallible allocation. +fn join_blob(gate: &[u8], up: &[u8], down: &[u8], gsize: usize, dsize: usize) -> Result> { + let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; + let mut blob = Vec::new(); + blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; + blob.extend_from_slice(gate); + blob.extend_from_slice(up); + blob.extend_from_slice(down); + Ok(blob.into_boxed_slice()) +} + +/// `rows * H` zeroed output floats in one fallible allocation. +fn zeroed_output(rows: usize) -> Result> { + let mut output = Vec::new(); + output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?; + output.resize(rows * H, 0.0); + Ok(output.into_boxed_slice()) +} + +/// The rows and the input of a job: 1..=MAX_ROWS rows of `H` finite floats. +fn validate_input(input: &[f32], rows: usize) -> Result<()> { + if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H { + return Err(Error::Shape); + } + if input.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFinite); + } + Ok(()) +} + +/// The block (values, bytes) of the gate/up and down formats and the byte sizes of one gate/up and the down matrix. +fn matrix_sizes(gu: GateUpFormat, down: DownFormat) -> ((usize, usize), (usize, usize), usize, usize) { + let (gq, gb) = gu.block(); + let (dq, db) = down.block(); + ((gq, gb), (dq, db), H / gq * gb * FF, FF / dq * db * H) +} + impl PreparedJob { pub fn new( gu: GateUpFormat, @@ -51,53 +103,20 @@ impl PreparedJob { input: Box<[f32]>, rows: usize, ) -> Result { - if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H { - return Err(Error::Shape); - } - if input.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFinite); - } - let (gq, gb) = gu.block(); - let (dq, db) = down.block(); - let gsize = H / gq * gb * FF; - let dsize = FF / dq * db * H; + validate_input(&input, rows)?; + let ((_, gb), (_, db), gsize, dsize) = matrix_sizes(gu, down); if gate.len() != gsize || up.len() != gsize || down_bytes.len() != dsize { return Err(Error::Shape); } - // Every admitted family has one FP16 header at each original block start. - // Integer multipliers are bounded; this is a guard, never a source proof. - for (bytes, block) in [(&gate, gb), (&up, gb), (&down_bytes, db)] { - for at in (0..bytes.len()).step_by(block) { - if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 { - return Err(Error::NonFinite); - } - } - } - let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; - let mut blob = Vec::new(); - blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; - blob.extend_from_slice(&gate); - blob.extend_from_slice(&up); - blob.extend_from_slice(&down_bytes); + validate_headers([(&gate[..], gb), (&up[..], gb), (&down_bytes[..], db)])?; + let blob = join_blob(&gate, &up, &down_bytes, gsize, dsize)?; // Drop original role owners before output allocation; all numerical // consumers will use this immutable complete native G|U|D owner. drop(gate); drop(up); drop(down_bytes); - let mut output = Vec::new(); - output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?; - output.resize(rows * H, 0.0); - Ok(Self { - gu, - down, - gate_bytes: gsize, - up_bytes: gsize, - down_bytes: dsize, - rows, - blob: blob.into_boxed_slice(), - input, - output: output.into_boxed_slice(), - }) + let output = zeroed_output(rows)?; + Ok(Self { gu, down, gate_bytes: gsize, up_bytes: gsize, down_bytes: dsize, rows, blob, input, output }) } pub fn owned_bytes(&self) -> Result { self.input @@ -128,7 +147,8 @@ impl DirectCpuPool { pub fn workers(&self) -> usize { self.workers } - /// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`). + /// `LELEKA_POOL_TIMING=1`: the host stage times of `compute_group` summed since the last call, in ms (see + /// `POOL_TIMING_STAGES`). pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { self.native.take_timing() } diff --git a/crates/native-cpu-expert/src/pool_plan.rs b/crates/native-cpu-expert/src/pool_plan.rs index 5f47b25b..27e37a40 100644 --- a/crates/native-cpu-expert/src/pool_plan.rs +++ b/crates/native-cpu-expert/src/pool_plan.rs @@ -1,16 +1,21 @@ -//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, commit `5ece068f`). +//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, +//! commit `5ece068f`). //! -//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the stack's default stays the -//! Original's 15 until the plan has a paired A/B on the machine it changes. On the 16-core 9950X3D of the server the plan gives 15 as well. +//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the +//! default of the stack stays the Original's 15 until the plan has a paired A/B on the machine it changes. On the +//! 16-core 9950X3D of the server the plan gives 15 as well. //! -//! Why a plan and not "every physical core but the host's": the pool's workers spin while they wait, so a worker without a core of its own takes -//! cycles from one that has one (a bigger count is slower, not just useless); the kernel is DRAM-bound, past the memory system's width more cores -//! add nothing and the barrier at the end of every layer waits for more threads; a container limited by a CFS quota still shows every core of the -//! machine. The pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at [`POOL_MAX_WORKERS`]. +//! Why a plan and not "every physical core but the host's": the workers of the pool spin while they wait, so a worker +//! without a core of its own takes cycles from one that has one (a bigger count is slower, not just useless); the +//! kernel is DRAM-bound, past the width of the memory system more cores add nothing and the barrier at the end of +//! every layer waits for more threads; a container limited by a CFS quota still shows every core of the machine. The +//! pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at +//! [`POOL_MAX_WORKERS`]. /// The pool's own ceiling (`NativePool::new` refuses more). pub const POOL_MAX_WORKERS: usize = 15; -/// Upstream's measured cap of a default count (`kPoolWorkersCap`); above the pool's ceiling here, kept so the mock-CPU tests match upstream's. +/// Upstream measured cap of a default count (`kPoolWorkersCap`); above the ceiling of the pool here, kept so the +/// mock-CPU tests match upstream. pub const WORKERS_CAP: usize = 32; /// A CPU with at least this many workers keeps [`RESERVE`] cores free for the engine's other threads. pub const RESERVE_FROM: usize = 16; @@ -21,7 +26,8 @@ pub const RESERVE: usize = 1; pub struct PoolPlanInput { /// Logical processors this process may run on. pub logical: usize, - /// Physical cores this process may use per CPU package, the host thread's package first (its own core is counted); empty = unknown. + /// Physical cores this process may use per CPU package, the package of the host thread first (its own core is + /// counted); empty = unknown. pub cores_per_package: Vec, /// CPUs a container quota allows (cgroup `cpu.max`); 0 = no quota. pub cpu_quota: f64, @@ -43,49 +49,90 @@ pub struct PoolPlan { pub limit: &'static str, } -pub fn plan_pool_workers(input: &PoolPlanInput) -> PoolPlan { - let mut cores: usize = input.cores_per_package.iter().sum(); - let mut local = input.cores_per_package.first().copied().unwrap_or(0); +/// The core layout the plan counts: physical cores (all packages and the host package), packages, and whether the OS +/// said which logical processors share a core. +struct Layout { + cores: usize, + local: usize, + packages: usize, + known: bool, +} + +/// The worker count so far and what bounded it (for the start-up line). +#[derive(Clone, Copy)] +struct Bound { + n: usize, + limit: &'static str, +} + +impl Bound { + /// The bound lowered to `candidate` (named `limit`) when that is below the count so far, else unchanged. + fn lowered_to(self, candidate: usize, limit: &'static str) -> Self { + if candidate < self.n { Self { n: candidate, limit } } else { self } + } +} + +fn read_layout(input: &PoolPlanInput) -> Layout { + let cores: usize = input.cores_per_package.iter().sum(); + let local = input.cores_per_package.first().copied().unwrap_or(0); let packages = input.cores_per_package.len().max(1); let known = !input.cores_per_package.is_empty() && cores > 0; - if !known { - // The OS did not say which logical processors share a core: counting every one as a core is what put a 256-thread machine at 255 workers. - cores = if input.logical >= 16 { input.logical / 2 } else { input.logical }; - local = cores; + if known { + return Layout { cores, local, packages, known }; } - let mut limit = "every physical core but the host's"; - let mut n = local.saturating_sub(1).max(1); // the host thread has the first core - if !known { - limit = "half the logical processors (the OS gave no core layout)"; - } else if packages > 1 { - limit = "the host's CPU socket"; + // The OS did not say which logical processors share a core: counting every one as a core is what put a 256-thread + // machine at 255 workers. + let cores = if input.logical >= 16 { input.logical / 2 } else { input.logical }; + Layout { cores, local: cores, packages, known } +} + +/// Every physical core but the host first (the host thread has the first core), bounded by the socket of the host. +fn host_bound(layout: &Layout) -> Bound { + let n = layout.local.saturating_sub(1).max(1); + let limit = if !layout.known { + "half the logical processors (the OS gave no core layout)" + } else if layout.packages > 1 { + "the host's CPU socket" + } else { + "every physical core but the host's" + }; + Bound { n, limit } +} + +/// A CPU with at least `RESERVE_FROM` workers keeps `RESERVE` cores free for the other threads of the engine. +fn keep_cores_free(bound: Bound, layout: &Layout) -> Bound { + if bound.n < RESERVE_FROM { + return bound; } - if n >= RESERVE_FROM { - n -= RESERVE; - if known && packages == 1 { - limit = "physical cores, one kept free"; - } + let limit = if layout.known && layout.packages == 1 { "physical cores, one kept free" } else { bound.limit }; + Bound { n: bound.n - RESERVE, limit } +} + +/// A hybrid CPU with more E-cores than P-cores: the P-cores but the host's plus half of the E-cores. +fn hybrid_workers(input: &PoolPlanInput) -> Option { + (input.p_cores > 0 && input.e_cores > input.p_cores).then(|| (input.p_cores - 1 + input.e_cores / 2).max(1)) +} + +/// The CPUs a container quota allows, less the host, at least one. +fn quota_workers(input: &PoolPlanInput) -> Option { + (input.cpu_quota > 0.0).then(|| ((input.cpu_quota as usize).saturating_sub(1)).max(1)) +} + +pub fn plan_pool_workers(input: &PoolPlanInput) -> PoolPlan { + let layout = read_layout(input); + let bound = keep_cores_free(host_bound(&layout), &layout); + let bound = hybrid_workers(input) + .map_or(bound, |h| bound.lowered_to(h, "the performance cores and half of the efficiency cores")); + let bound = quota_workers(input).map_or(bound, |q| bound.lowered_to(q, "the container's CPU quota")); + let bound = bound.lowered_to(WORKERS_CAP, "the measured cap"); + PoolPlan { + workers: bound.n.max(1), + cores: layout.cores, + cores_local: layout.local, + packages: layout.packages, + topology_known: layout.known, + limit: bound.limit, } - if input.p_cores > 0 && input.e_cores > input.p_cores { - // a hybrid CPU with more E-cores than P-cores: the P-cores but the host's plus half of the E-cores - let h = (input.p_cores - 1 + input.e_cores / 2).max(1); - if h < n { - n = h; - limit = "the performance cores and half of the efficiency cores"; - } - } - if input.cpu_quota > 0.0 { - let q = ((input.cpu_quota as usize).saturating_sub(1)).max(1); - if q < n { - n = q; - limit = "the container's CPU quota"; - } - } - if n > WORKERS_CAP { - n = WORKERS_CAP; - limit = "the measured cap"; - } - PoolPlan { workers: n.max(1), cores, cores_local: local, packages, topology_known: known, limit } } /// The CPU this process runs on, as far as this build can read it.