From 4726afa27ee3a807de2570f2e1fda3ce0cbf5662 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 19:32:17 +0200 Subject: [PATCH] perf(cpu-expert): pin the host loop once to the first physical core (session.cpp SessionLoopScratch) The direct pool's caller drains beside the workers, which are pinned to every physical core but the first. Like the Original's session loop, the caller is now pinned once (on its first group) to that free core and its previous mask is restored when the pool drops; unpinned, its drain and doorbell spin can land on a worker's core or SMT sibling (the Original measured 26.9 vs 36.3 GB/s for this). Placement only: no arithmetic changes. LELEKA_CPU_POOL_PIN_HOST=off is the A/B arm. Co-Authored-By: Claude Opus 5.5 --- crates/native-cpu-expert/src/lib.rs | 26 +++++++++++++++++-- crates/native-cpu-expert/src/rust_platform.rs | 11 ++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index c0dd8254..ff392c90 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -122,18 +122,34 @@ pub const MAX_OUT_ROWS: usize = 128; /// beside the workers (pool.cpp `host_works_`), so nothing crosses a thread boundary by value and every /// borrow ends when `compute_group` returns. The encoded bytes are the caller's admitted matrices: this /// crate checks extents, pair bounds, disjoint destinations and finite inputs/outputs, never the source. -pub struct DirectCpuPool { native: ffi::NativePool, workers: usize, failed: bool, _actor: PhantomData> } +pub struct DirectCpuPool { + native: ffi::NativePool, workers: usize, failed: bool, + /// session.cpp `SessionLoopScratch`: the caller (the host loop, which drains beside the workers) is pinned + /// once to the first physical core, the one the workers leave free; its previous mask is restored on drop. + pin_host: bool, host_mask: Option<[usize; 16]>, + _actor: PhantomData>, +} impl DirectCpuPool { pub fn new(workers: i32) -> Result { let native = ffi::NativePool::new(workers)?; let workers = native.workers()?; - Ok(Self { native, workers, failed: false, _actor: PhantomData }) + let pin_host = std::env::var("LELEKA_CPU_POOL_PIN_HOST").as_deref() != Ok("off"); + Ok(Self { native, workers, failed: false, pin_host, host_mask: None, _actor: PhantomData }) + } + fn pin_caller(&mut self) { + if self.pin_host && self.host_mask.is_none() { + if let (Some(mask), Some(&core)) = (rust_platform::current_affinity(), rust_platform::cores(false).first()) { + self.host_mask = Some(mask); + rust_platform::pin(core); + } + } } pub fn workers(&self) -> usize { self.workers } /// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts, /// all of the same gate/up and down formats). Only the pairs' rows of `out` are written. pub fn compute_group(&mut self, gu: GateUpFormat, down: DownFormat, group: &BorrowedGroup<'_>, out: &mut [f32]) -> Result<()> { if self.failed { return Err(Error::Closed); } + self.pin_caller(); let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out); if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } result @@ -148,6 +164,12 @@ impl DirectCpuPool { } } +impl Drop for DirectCpuPool { + fn drop(&mut self) { + if let Some(mask) = self.host_mask.take() { rust_platform::restore_affinity(&mask); } + } +} + pub struct CompletedJob { values: Box<[f32]> } impl CompletedJob { pub fn into_values(self) -> Box<[f32]> { self.values } } diff --git a/crates/native-cpu-expert/src/rust_platform.rs b/crates/native-cpu-expert/src/rust_platform.rs index c49e4aba..b46607e9 100644 --- a/crates/native-cpu-expert/src/rust_platform.rs +++ b/crates/native-cpu-expert/src/rust_platform.rs @@ -10,6 +10,7 @@ unsafe extern "C" { fn sched_getaffinity(pid:i32,bytes:usize,set:*mut usize)->i32; fn pthread_self()->usize; fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32; + fn pthread_getaffinity_np(thread:usize,bytes:usize,set:*mut usize)->i32; fn sysconf(name:i32)->i64; fn madvise(addr:*mut u8,len:usize,advice:i32)->i32; } @@ -48,6 +49,16 @@ pub(super) fn will_need(bytes:&[u8]) { // changes the contents or the mapping. unsafe {let _=madvise(start as *mut u8,end-start,3);} } +/// The calling thread's affinity mask (to restore after `pin`). +pub(super) fn current_affinity()->Option<[usize;16]> { + let mut set=[0usize;16]; + // SAFETY: initialized cpu_set_t-sized mask of the calling thread, no pointer retention. + (unsafe {pthread_getaffinity_np(pthread_self(),std::mem::size_of_val(&set),set.as_mut_ptr())}==0).then_some(set) +} +pub(super) fn restore_affinity(set:&[usize;16]) { + // SAFETY: as `pin`; a refusal leaves the thread where it is. + unsafe {let _=pthread_setaffinity_np(pthread_self(),std::mem::size_of_val(set),set.as_ptr());} +} pub(super) fn pin(core:i32) { if core<0{return;}let mut set=[0usize;16];if core as usize>=1024{return;}set[core as usize/64]|=1usize<<(core as usize%64); // Original intentionally ignores OS affinity refusal; it does not change math.