Skip to content
Merged
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
391 changes: 348 additions & 43 deletions crates/celox/src/backend/native/backend.rs

Large diffs are not rendered by default.

194 changes: 190 additions & 4 deletions crates/celox/src/backend/native/compile_resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,62 @@

const MAX_WORKERS: usize = 4;

/// Dispatch in priority order, but return results in stable task-index order.
/// Each worker owns at most one expanded process and its compilation state.
pub(super) fn compile_tasks<T: Send>(
order: &[usize],
workers: usize,
compile: impl Fn(usize) -> T + Sync,
) -> std::thread::Result<Vec<T>> {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut results = if workers <= 1 || order.len() <= 1 {
order
.iter()
.map(|&index| (index, compile(index)))
.collect::<Vec<_>>()
} else {
let next = AtomicUsize::new(0);
std::thread::scope(|scope| {
let handles = (0..workers.min(order.len()))
.map(|_| {
let next = &next;
let compile = &compile;
scope.spawn(move || {
let mut results = Vec::new();
loop {
let position = next.fetch_add(1, Ordering::Relaxed);
let Some(&index) = order.get(position) else {
break;
};
results.push((index, compile(index)));
}
results
})
})
.collect::<Vec<_>>();
let mut results = Vec::new();
let mut panic = None;
for handle in handles {
match handle.join() {
Ok(completed) => results.extend(completed),
Err(error) => {
if panic.is_none() {
panic = Some(error);
}
}
}
}
if let Some(error) = panic {
Err(error)
} else {
Ok(results)
}
})?
};
results.sort_unstable_by_key(|(index, _)| *index);
Ok(results.into_iter().map(|(_, result)| result).collect())
}

pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize {
choose_workers(
blocks,
Expand All @@ -12,6 +68,52 @@ pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize
)
}

/// One primary circuit and a queue of smaller independent event functions.
/// Reserve the primary once, rather than charging its size to every worker.
pub(super) fn workers_with_primary(
primary: (usize, usize),
secondary: (usize, usize),
tasks: usize,
) -> usize {
choose_workers_with_primary(
primary,
secondary,
tasks,
std::thread::available_parallelism().map_or(1, usize::from),
available_memory(),
)
}

fn choose_workers_with_primary(
primary: (usize, usize),
secondary: (usize, usize),
tasks: usize,
cpus: usize,
available: Option<u64>,
) -> usize {
let maximum = MAX_WORKERS.min(cpus.max(1)).min(tasks.saturating_add(1));
let Some(available) = available else {
return choose_workers(
primary.0.max(secondary.0),
primary.1.max(secondary.1),
tasks.saturating_add(1),
cpus,
None,
);
};
let budget = available - available / 5;
let remaining = budget.saturating_sub(estimated_memory(primary.0, primary.1));
1 + (remaining / estimated_memory(secondary.0, secondary.1))
.min(maximum.saturating_sub(1) as u64) as usize
}

fn estimated_memory(blocks: usize, instructions: usize) -> u64 {
(blocks as u64)
.saturating_mul(24 * 1024)
.max((instructions as u64).saturating_mul(4096))
.max(128 * 1024 * 1024)
}

fn choose_workers(
blocks: usize,
instructions: usize,
Expand All @@ -30,10 +132,7 @@ fn choose_workers(
// eight-hart functions peaked at 6.54 GiB for the entire process tree.
// Account for straight-line designs too, not only CFG size.
// These are conservative estimates, not reservations or memory limits.
let per_function = (blocks as u64)
.saturating_mul(24 * 1024)
.max((instructions as u64).saturating_mul(4096))
.max(128 * 1024 * 1024);
let per_function = estimated_memory(blocks, instructions);
// Leave room for the running simulator and unrelated host activity.
let budget = available - available / 5;
(budget / per_function).min(maximum as u64).max(1) as usize
Expand Down Expand Up @@ -154,6 +253,93 @@ mod tests {

const GIB: u64 = 1024 * 1024 * 1024;

#[test]
fn primary_worker_budget_keeps_capacity_for_smaller_functions() {
let primary = (65_536, 1_000_000);
let small = (100, 1_000);
assert_eq!(
choose_workers_with_primary(primary, small, 10, 16, Some(8 * GIB)),
4
);
assert_eq!(
choose_workers_with_primary(primary, primary, 10, 16, Some(8 * GIB)),
1
);
assert_eq!(
choose_workers_with_primary(primary, small, 10, 16, Some(4 * GIB)),
1
);
assert_eq!(
choose_workers_with_primary(primary, small, 0, 16, Some(8 * GIB)),
1
);
assert_eq!(
choose_workers_with_primary(primary, small, 10, 2, Some(8 * GIB)),
2
);
assert_eq!(
choose_workers_with_primary((120_000, 1), small, 10, 16, None),
1
);
for available in [0, GIB, 4 * GIB, 5 * GIB, 8 * GIB, u64::MAX] {
for secondary in [small, primary, (usize::MAX, usize::MAX)] {
let workers =
choose_workers_with_primary(primary, secondary, 10, 16, Some(available));
assert!((1..=MAX_WORKERS).contains(&workers));
if workers > 1 {
let reserved = u128::from(estimated_memory(primary.0, primary.1))
+ (workers - 1) as u128
* u128::from(estimated_memory(secondary.0, secondary.1));
assert!(reserved <= u128::from(available - available / 5));
}
}
}
}

#[test]
fn indexed_tasks_keep_results_ordered_and_bound_active_work() {
use std::sync::atomic::{AtomicUsize, Ordering};
let order = (0..16).rev().collect::<Vec<_>>();
for workers in [1, 2, 4] {
let active = AtomicUsize::new(0);
let peak = AtomicUsize::new(0);
let seen = AtomicUsize::new(0);
let results = compile_tasks(&order, workers, |index| {
let count = active.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(count, Ordering::SeqCst);
seen.fetch_or(1 << index, Ordering::SeqCst);
std::thread::yield_now();
active.fetch_sub(1, Ordering::SeqCst);
index * 3
})
.unwrap();
assert_eq!(results, (0..16).map(|index| index * 3).collect::<Vec<_>>());
assert_eq!(seen.load(Ordering::SeqCst), (1 << 16) - 1);
assert_eq!(active.load(Ordering::SeqCst), 0);
assert!(peak.load(Ordering::SeqCst) <= workers);
}
}

#[test]
fn indexed_tasks_preserve_errors_and_return_worker_panics() {
let results = compile_tasks(&[3, 2, 1, 0], 2, |index| {
if index == 1 || index == 3 {
Err(index)
} else {
Ok(index)
}
})
.unwrap();
assert_eq!(results.into_iter().collect::<Result<Vec<_>, _>>(), Err(1));
assert!(
compile_tasks(&[0, 1, 2], 2, |index| {
assert_ne!(index, 1, "worker panic probe");
index
})
.is_err()
);
}

#[cfg(target_os = "linux")]
#[test]
fn finite_process_limit_caps_the_worker_memory_budget() {
Expand Down
4 changes: 2 additions & 2 deletions crates/celox/src/backend/native/image_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use std::{fmt, path::Path};
use super::backend::NativeProgramImage;

const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI";
// Compound event probes extend the fork activation image format.
const CONTAINER_VERSION: u16 = 47;
// Native kernel offsets extend the image metadata.
const CONTAINER_VERSION: u16 = 48;
const TRAILER_SIZE: usize = 32;
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
Expand Down
123 changes: 117 additions & 6 deletions crates/celox/src/derived_edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,49 @@ impl EdgePlan {
/// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit
/// reads the scheduler's dirty flag to know whether to settle first.
pub(crate) fn attach(program: &mut LaidOutProgram) {
attach_with_mode(program, false);
}

/// Reserve native entry indices without retaining a copy of the full circuit
/// for both polarities of every derived-clock event.
pub(crate) fn attach_deferred(program: &mut LaidOutProgram) {
attach_with_mode(program, true);
}

#[derive(Clone, Debug)]
pub(crate) struct DeferredEdge {
event: AbsoluteAddr,
rising: bool,
fires: bool,
flag: AbsoluteAddr,
pub(crate) blocks: usize,
pub(crate) instructions: usize,
}

impl DeferredEdge {
pub(crate) fn generate(
&self,
program: &LaidOutProgram,
model: &ScheduleModel<AbsoluteAddr>,
) -> Result<Unit, &'static str> {
self.generate_with_comb(program, model, &program.sir.eval_comb)
}

pub(crate) fn generate_with_comb(
&self,
program: &LaidOutProgram,
model: &ScheduleModel<AbsoluteAddr>,
comb: &[Unit],
) -> Result<Unit, &'static str> {
let plan = EdgePlan::new(program, model, self.event)?
.ok_or("deferred derived edge no longer has a plan")?;
let mut unit = plan.unit(comb, self.rising, self.fires, Settle::Flag(self.flag));
crate::settle::instrument_unit(program, &mut unit);
Ok(unit)
}
}

fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) {
let schema = &program.runtime.runtime_schema;
let Some(flag) = schema
.scheduler
Expand Down Expand Up @@ -815,14 +858,81 @@ pub(crate) fn attach(program: &mut LaidOutProgram) {
_ => true,
};
let mut indices = [0usize; 2];
for (index, rising) in [true, false].into_iter().enumerate() {
let unit = plan.unit(
&program.sir.eval_comb,
rising,
fires(rising),
Settle::Flag(flag),
// Include both settles and every possible FF path. The control-flow
// allowance also covers gate expressions and per-unit continuations.
let (estimated_blocks, estimated_instructions) = if deferred {
let units = program
.sir
.eval_comb
.iter()
.chain(&program.sir.eval_comb)
.chain(plan.entries().flat_map(|units| {
units
.eval_apply
.iter()
.chain(units.eval_only.as_ref().unwrap_or(&units.eval_apply))
.chain(units.apply.iter().flatten())
}));
let gate_ops = plan.gated.iter().map(|gate| gate.gate.len()).sum::<usize>();
units.fold(
(
1024usize,
8192usize.saturating_add(gate_ops.saturating_mul(16)),
),
|(blocks, instructions), unit| {
(
blocks.saturating_add(unit.blocks.len()).saturating_add(2),
instructions.saturating_add(
unit.blocks
.values()
.map(|b| b.instructions.len())
.sum::<usize>(),
),
)
},
)
} else {
(0, 0)
};
if deferred {
tracing::debug!(
"[derived-edge-size] event={} kind={:?} blocks={} instructions={}",
program.get_path(&event),
kind,
estimated_blocks,
estimated_instructions,
);
}
for (index, rising) in [true, false].into_iter().enumerate() {
indices[index] = program.sir.processes.len();
let unit = if deferred {
program.deferred_derived_edges.insert(
indices[index],
DeferredEdge {
event,
rising,
fires: fires(rising),
flag,
blocks: estimated_blocks,
instructions: estimated_instructions,
},
);
let mut builder = Builder::new();
builder.seal_block(SIRTerminator::Return);
let (blocks, register_map, _) = builder.drain();
Unit {
entry_block_id: BlockId(0),
blocks,
register_map,
}
} else {
plan.unit(
&program.sir.eval_comb,
rising,
fires(rising),
Settle::Flag(flag),
)
};
program.sir.processes.push(unit);
}
edges.push(celox_design::DerivedEdgeUnits {
Expand All @@ -848,6 +958,7 @@ pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram {
.min();
if let Some(first) = first {
program.sir.processes.truncate(first);
program.deferred_derived_edges.clear();
program.runtime.runtime_schema.derived_edges.clear();
}
program
Expand Down
7 changes: 7 additions & 0 deletions crates/celox/src/dpi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,13 @@ impl Default for ExternFunctionTable {
}

impl ExternFunctionTable {
/// Append image-local compiled callees after the DPI imports.
pub(crate) fn append_native_kernels(&mut self, addresses: impl IntoIterator<Item = usize>) {
let mut table = self.addresses.to_vec();
table.extend(addresses);
self.addresses = table.into();
}

/// The user table's address, which the state header holds. The internal
/// floating-point helper occupies the immediately preceding slot, and the
/// heap helper the one before it.
Expand Down
Loading
Loading