Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions eos/src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,155 @@ pub fn raise_open_file_limit(desired: u64) -> Option<u64> {
Some(current)
}

/// Select the high-capacity CPU subset from `(cpu_id, cpu_capacity)` pairs
/// when the allowed set spans asymmetric core tiers (such as ARM big.LITTLE).
///
/// Returns `None` when the allowed set is homogeneous, contains fewer than two
/// CPUs, has invalid zero capacities, or would collapse below two CPUs.
pub fn select_high_capacity_cpus(allowed_with_capacity: &[(usize, u32)]) -> Option<Vec<usize>> {
if allowed_with_capacity.len() < 2 {
return None;
}
let mut min_cap = u32::MAX;
let mut max_cap = 0u32;
for &(_, cap) in allowed_with_capacity {
if cap == 0 {
return None;
}
min_cap = min_cap.min(cap);
max_cap = max_cap.max(cap);
}
if min_cap == max_cap {
return None;
}
// Performance cores on asymmetric SoCs can differ by a few percent across
// clusters (for example, ACPI CPPC capacities 997..1024 vs efficiency 718..731).
let mut selected: Vec<usize> = allowed_with_capacity
.iter()
.filter(|&&(_, cap)| u64::from(cap) * 10 >= u64::from(max_cap) * 9)
.map(|&(cpu, _)| cpu)
.collect();
if selected.len() < 2 {
// Avoid collapsing multiple busy threads onto a single prime core on
// three-tier topologies: fall back to all cores above the capacity midpoint.
let sum = u64::from(min_cap) + u64::from(max_cap);
selected = allowed_with_capacity
.iter()
.filter(|&&(_, cap)| u64::from(cap) * 2 > sum)
.map(|&(cpu, _)| cpu)
.collect();
}
if selected.len() >= 2 && selected.len() < allowed_with_capacity.len() {
Some(selected)
} else {
None
}
}

/// Restrict the calling thread to high-capacity CPUs within its current
/// affinity mask on asymmetric Linux systems. No-op on homogeneous CPUs,
/// restricted cpusets that already cover one tier, or non-Linux targets.
#[cfg(target_os = "linux")]
pub fn prefer_high_capacity_cpus() {
let mut allowed: libc::cpu_set_t = unsafe { std::mem::zeroed() };
if unsafe { libc::sched_getaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mut allowed) }
!= 0
{
return;
}
let max_cpus = std::mem::size_of::<libc::cpu_set_t>() * 8;
let mut allowed_with_capacity = Vec::new();
for cpu in 0..max_cpus {
if unsafe { libc::CPU_ISSET(cpu, &allowed) } {
let path = format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity");
let Ok(text) = std::fs::read_to_string(&path) else {
return;
};
let Ok(cap) = text.trim().parse::<u32>() else {
return;
};
allowed_with_capacity.push((cpu, cap));
}
}
let Some(selected) = select_high_capacity_cpus(&allowed_with_capacity) else {
return;
};
let mut next: libc::cpu_set_t = unsafe { std::mem::zeroed() };
for cpu in selected {
unsafe { libc::CPU_SET(cpu, &mut next) };
}
let _ = unsafe { libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &next) };
}

#[cfg(not(target_os = "linux"))]
pub fn prefer_high_capacity_cpus() {}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn select_high_capacity_cpus_splits_asymmetric_tiers() {
let mut gb10 = Vec::new();
for cpu in 0..5 {
gb10.push((cpu, 718));
}
for cpu in 5..10 {
gb10.push((cpu, 997));
}
for cpu in 10..15 {
gb10.push((cpu, 731));
}
for cpu in 15..19 {
gb10.push((cpu, 1017));
}
gb10.push((19, 1024));
assert_eq!(
select_high_capacity_cpus(&gb10),
Some(vec![5, 6, 7, 8, 9, 15, 16, 17, 18, 19])
);
}

#[test]
fn select_high_capacity_cpus_is_noop_on_homogeneous_or_single_tier_cpuset() {
let homogeneous: Vec<_> = (0..16).map(|cpu| (cpu, 1024)).collect();
assert_eq!(select_high_capacity_cpus(&homogeneous), None);

let efficiency_only: Vec<_> = (0..5)
.map(|cpu| (cpu, 718))
.chain((10..15).map(|cpu| (cpu, 731)))
.collect();
assert_eq!(select_high_capacity_cpus(&efficiency_only), None);

let performance_only: Vec<_> = (5..10)
.map(|cpu| (cpu, 997))
.chain((15..19).map(|cpu| (cpu, 1017)))
.chain(std::iter::once((19, 1024)))
.collect();
assert_eq!(select_high_capacity_cpus(&performance_only), None);

assert_eq!(select_high_capacity_cpus(&[(19, 1024)]), None);
assert_eq!(select_high_capacity_cpus(&[(0, 0), (1, 1024)]), None);
}

#[test]
fn select_high_capacity_cpus_avoids_single_core_collapse_on_three_tier_soc() {
let three_tier = vec![
(0, 400),
(1, 400),
(2, 400),
(3, 400),
(4, 850),
(5, 850),
(6, 850),
(7, 1024),
];
assert_eq!(
select_high_capacity_cpus(&three_tier),
Some(vec![4, 5, 6, 7])
);
}

#[test]
fn raise_open_file_limit_never_lowers_and_respects_hard_limit() {
let mut before: libc::rlimit = unsafe { std::mem::zeroed() };
Expand Down
3 changes: 3 additions & 0 deletions eos/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ pub fn raise_open_file_limit(_desired: u64) -> Option<u64> {
None
}

/// CPU capacity affinity narrowing is implemented for asymmetric Linux topologies.
pub fn prefer_high_capacity_cpus() {}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
71 changes: 71 additions & 0 deletions helios/native/roce_proxy.c
Original file line number Diff line number Diff line change
Expand Up @@ -1502,8 +1502,79 @@ static int run_varlen_op(roce_ctx_t* c, uint32_t seq, uint32_t nbytes, uint32_t
return drain_all(c);
}

#ifdef __linux__
// Restrict the proxy polling thread to high-capacity CPUs within its current
// affinity mask on asymmetric Linux systems (such as ARM big.LITTLE). No-op
// when sysfs cpu_capacity is absent, homogeneous, already restricted to one
// tier, or would collapse below two CPUs.
static void pin_high_capacity_cpus(void) {
cpu_set_t allowed;
CPU_ZERO(&allowed);
if (sched_getaffinity(0, sizeof(allowed), &allowed) != 0) {
return;
}
int cpus[CPU_SETSIZE];
uint32_t caps[CPU_SETSIZE];
int count = 0;
uint32_t min_cap = UINT32_MAX;
uint32_t max_cap = 0;
for (int cpu = 0; cpu < CPU_SETSIZE; cpu++) {
if (!CPU_ISSET(cpu, &allowed)) {
continue;
}
char path[128];
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu);
FILE* f = fopen(path, "r");
if (f == NULL) {
return;
}
unsigned long val = 0;
int matched = fscanf(f, "%lu", &val);
fclose(f);
if (matched != 1 || val == 0 || val > UINT32_MAX) {
return;
}
cpus[count] = cpu;
caps[count] = (uint32_t)val;
if (caps[count] < min_cap) min_cap = caps[count];
if (caps[count] > max_cap) max_cap = caps[count];
count++;
}
if (count < 2 || min_cap == max_cap) {
return;
}
cpu_set_t next;
CPU_ZERO(&next);
int selected = 0;
for (int i = 0; i < count; i++) {
if ((uint64_t)caps[i] * 10 >= (uint64_t)max_cap * 9) {
CPU_SET(cpus[i], &next);
selected++;
}
}
if (selected < 2) {
CPU_ZERO(&next);
selected = 0;
uint64_t sum = (uint64_t)min_cap + (uint64_t)max_cap;
for (int i = 0; i < count; i++) {
if ((uint64_t)caps[i] * 2 > sum) {
CPU_SET(cpus[i], &next);
selected++;
}
}
}
if (selected >= 2 && selected < count) {
(void)sched_setaffinity(0, sizeof(next), &next);
}
}
#endif

static void* proxy_main(void* arg) {
roce_ctx_t* c = (roce_ctx_t*)arg;
#ifdef __linux__
(void)pthread_setname_np(pthread_self(), "flare-roce");
pin_high_capacity_cpus();
#endif
volatile uint32_t* ctrl = (volatile uint32_t*)(c->region + c->ctrl_off);
// Spin while ops are flowing. After ROCE_IDLE_SPINS polls without a
// doorbell, request a short nanosleep between polls (the OS decides the
Expand Down
1 change: 1 addition & 0 deletions helios/src/execution/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@ pub unsafe fn serve_rank(
}
};
executor.copy_logprobs = false;
flare_eos::prefer_high_capacity_cpus();
let result = (|| -> Result<()> {
if world < 2 || !(1..world).contains(&rank) {
return Err(invalid("invalid tensor-parallel peer identity"));
Expand Down
1 change: 1 addition & 0 deletions helios/src/execution/threaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,7 @@ impl ThreadedExecutor {
}
};
executor.copy_logprobs = false;
flare_eos::prefer_high_capacity_cpus();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rank_loop(index, &mut executor, commands, &replies, &peer_ring)
}))
Expand Down
1 change: 1 addition & 0 deletions helios/src/execution/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ impl ExecutionWorker {
};
}
};
flare_eos::prefer_high_capacity_cpus();
let _ = ready_sender.send(Ok(()));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
while let Ok(command) = receiver.recv() {
Expand Down
5 changes: 4 additions & 1 deletion helios/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ impl ReplayWorker {
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
let thread = thread::Builder::new()
.name("flare-cuda".into())
.spawn(move || run(receiver, completion_sender, ready_sender))
.spawn(move || {
flare_eos::prefer_high_capacity_cpus();
run(receiver, completion_sender, ready_sender)
})
.map_err(|e| {
ExecutionError::Worker(Failure::caused_by(
format!("cannot start native replay worker: {e}"),
Expand Down
4 changes: 4 additions & 0 deletions helios/src/server/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,10 @@ impl ModelRuntime {
if worker.config.contract.vision.enabled() {
worker.image_preparation = Some(ImagePreparation::new(worker_input_store));
}
// Narrow affinity only after RankExecutor, host offload/codec/disk, and image
// preparation child threads have been spawned so background workers stay free
// to run on efficiency cores and observe the full process cpuset.
flare_eos::prefer_high_capacity_cpus();
worker_metrics.scheduler(worker.scheduler.stats());
worker_health.store(true, Ordering::Release);
let _ = ready_tx.send(Ok(()));
Expand Down