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
6 changes: 6 additions & 0 deletions crates/celox-frontend-core/src/symbolic/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ pub struct ParallelScheduleOptions {
/// value between paths leave the program (`celox_slt::net_inline`).
/// [`DeadStorePolicy::Off`] keeps every net.
pub unobserved_nets: DeadStorePolicy,
/// The threads the frontend may lower independent modules on, at least
/// one: one lowers them in order on the calling thread. They are not
/// simulation lanes; what the frontend makes is the same for every
/// count.
pub compile_workers: usize,
}

/// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]).
Expand All @@ -62,6 +67,7 @@ impl ParallelScheduleOptions {
settle: SettlePartitionMode::Off,
settle_profile: false,
unobserved_nets: DeadStorePolicy::Off,
compile_workers: 1,
};

/// Request `lanes` simulation lanes with the default cost model.
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-frontend-sv/src/lowering/external_hierarchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,8 @@ fn prepare_external_hierarchy_collecting(
time_format,
&expansion,
),
// A mixed-language hierarchy is lowered on the calling thread.
1,
module_ids.len(),
four_state,
false,
Expand Down
99 changes: 96 additions & 3 deletions crates/celox-frontend-sv/src/lowering/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,12 @@ struct PackageLowering {
lowered: Result<(String, ModuleId, LoweredSvModule), sv::AnalyzerError>,
}

/// Each state module is lowered on its own, on up to `workers` threads, the
/// largest first.
#[allow(clippy::too_many_arguments)]
pub(super) fn lower_package_states(
states: PackageStates,
workers: usize,
first: usize,
four_state: bool,
ff_parts: bool,
Expand All @@ -116,12 +120,14 @@ pub(super) fn lower_package_states(
} = states;
// Each module is lowered on its own; what they give is passed on in
// their order, up to the first that fails, as lowering them one after
// another would.
let order = (0..states.len()).collect::<Vec<_>>();
// another would. The largest start first: a package of a class library
// such as UVM carries thousands of subroutines.
let mut order = (0..states.len()).collect::<Vec<_>>();
order.sort_by_key(|&index| std::cmp::Reverse(states[index].0.subroutines().len()));
let lowerings = celox_frontend_core::tasks::run_owned::<_, _, std::convert::Infallible>(
states,
&order,
1,
workers,
|index, (module, time_scale)| {
let mut warnings = Vec::new();
let mut report = None;
Expand Down Expand Up @@ -337,3 +343,90 @@ pub(super) fn bind_package_variables<'a>(
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::super::{FrontendTraceOptions, schedule_sources_with_options, sv};
use std::sync::Arc;

/// The SIR, or the error, and the warnings and recursion report lines of
/// scheduling `source` with `workers` compile threads.
fn schedule(source: &str, workers: usize, name: &str) -> (String, String, String) {
let report = std::env::temp_dir().join(format!(
"celox-package-states-{}-{name}-{workers}.txt",
std::process::id()
));
let _ = std::fs::remove_file(&report);
let mut warnings = Vec::new();
let scheduled = schedule_sources_with_options(
&[(source, std::path::Path::new("packages.sv"))],
"Top",
&[],
&[],
&[],
false,
&celox_frontend_core::ParallelScheduleOptions {
compile_workers: workers,
..Default::default()
},
&FrontendTraceOptions::default(),
None,
&mut warnings,
sv::AnalysisOptions {
recursion_report: Some(Arc::from(report.as_path())),
..sv::AnalysisOptions::default()
},
);
let result = match scheduled {
Ok(output) => format!("{:?}", output.scheduled.sir),
Err(error) => format!("error {error:?}"),
};
let lines = std::fs::read_to_string(&report).unwrap_or_default();
let _ = std::fs::remove_file(&report);
(result, format!("{warnings:?}"), lines)
}

/// Lowering the state modules of the packages on several threads makes
/// what lowering them one after another makes: the same SIR, warnings
/// and recursion report.
#[test]
fn package_states_lower_alike_on_any_number_of_threads() {
let packages = (0..6)
.map(|index| {
format!(
"package p{index};
int counter = {index};
class C{index};
static int made = 0;
function new(); made = made + 1; endfunction
virtual function int value(int n);
if (n > 0) return value(n - 1) + {index};
return counter;
endfunction
endclass
C{index} first = new();
int start = first.value(2);
endpackage
"
)
})
.collect::<String>();
let source = format!(
"{packages}
module Top(output int sum);
assign sum = p0::start + p1::start + p2::start + p3::start
+ p4::start + p5::start;
endmodule"
);
let sequential = schedule(&source, 1, "ok");
assert!(!sequential.0.starts_with("error "), "{}", sequential.0);
assert!(!sequential.2.is_empty(), "no recursion report");
for workers in [2, 4, 16] {
assert_eq!(
schedule(&source, workers, "ok"),
sequential,
"{workers} threads"
);
}
}
}
1 change: 1 addition & 0 deletions crates/celox-frontend-sv/src/lowering/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1227,6 +1227,7 @@ fn schedule_sources_collecting(
}
let package_states = lower_package_states(
package_states,
parallel.compile_workers,
module_ids.len(),
four_state,
parallel.enabled(),
Expand Down
13 changes: 13 additions & 0 deletions crates/celox-napi/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ pub struct NapiOptions {
pub dead_store_policy: Option<String>,
/// Simulation threads, including the calling thread. Default: 1.
pub threads: Option<u32>,
/// Compile threads (see `SimulatorBuilder::compile_threads`). Default:
/// the available parallelism of the host.
pub compile_threads: Option<u32>,
/// Tiered handles compile hot execution groups incrementally (hotspot
/// JIT). Default: true; `false` selects whole-image tiered compilation.
pub hotspot_jit: Option<bool>,
Expand Down Expand Up @@ -458,6 +461,16 @@ pub(super) fn parse_options(options: &Option<NapiOptions>) -> Result<ParsedOptio
.optimize_options
.set_parallel_lanes(threads.min(celox::MAX_SIMULATION_THREADS));
}
if let Some(threads) = o.compile_threads {
if threads == 0 {
return Err(Error::from_reason(
"Invalid compileThreads 0. Expected at least 1.".to_string(),
));
}
common
.optimize_options
.set_compile_threads(threads as usize);
}
let dead_store_policy = o
.dead_store_policy
.as_deref()
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-napi/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ fn native_handle_dumps_consume_activity_until_memory_is_exposed() {
parameters: None,
dead_store_policy: None,
threads: None,
compile_threads: None,
hotspot_jit: None,
});
let mut handle = if mode == "tiered" {
Expand Down Expand Up @@ -234,6 +235,7 @@ fn fst_option_records_a_parseable_waveform_and_conflicts_with_vcd() {
parameters: None,
dead_store_policy: None,
threads: None,
compile_threads: None,
hotspot_jit: None,
})
}
Expand Down
32 changes: 32 additions & 0 deletions crates/celox-sir-opt/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ pub struct OptimizeOptions {
disabled: HashSet<SirPass>,
max_native_memory_width: usize,
parallel_lanes: u32,
/// See [`Self::compile_threads`]; `None` takes the available
/// parallelism.
compile_threads: Option<usize>,
parallel_partition: ParallelPartition,
settle_partition: SettlePartition,
settle_profile: bool,
Expand Down Expand Up @@ -241,6 +244,7 @@ impl OptimizeOptions {
64
},
parallel_lanes: 1,
compile_threads: None,
parallel_partition: ParallelPartition::Estimated,
settle_partition: SettlePartition::Estimated,
settle_profile: false,
Expand Down Expand Up @@ -309,6 +313,34 @@ impl OptimizeOptions {
self.parallel_lanes.max(1)
}

/// Compile with at most `threads` threads (at least one): the frontend
/// lowers independent modules on them, and native code generation
/// compiles independent units on as many of them as its memory budget
/// allows. One compiles everything on the calling thread. They are not
/// simulation lanes (see [`Self::set_parallel_lanes`]); the result is the
/// same for every count. The default is the available parallelism of
/// the host.
pub fn with_compile_threads(mut self, threads: usize) -> Self {
self.set_compile_threads(threads);
self
}

pub fn set_compile_threads(&mut self, threads: usize) {
self.compile_threads = Some(threads.max(1));
}

/// The compile threads set with [`Self::with_compile_threads`], if any.
pub fn requested_compile_threads(&self) -> Option<usize> {
self.compile_threads
}

/// The threads compiling may use (see [`Self::with_compile_threads`]).
pub fn compile_threads(&self) -> usize {
self.compile_threads.unwrap_or_else(|| {
std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
})
}

pub fn with_parallel_partition(mut self, partition: ParallelPartition) -> Self {
self.parallel_partition = partition;
self
Expand Down
5 changes: 5 additions & 0 deletions crates/celox/src/backend/native/backend/compile_program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ pub(super) fn compile_program_with_outlining_threshold(
0
});
let workers = super::super::compile_resources::workers_with_primary(
options.optimize_options.compile_threads(),
comb_size,
(pool_blocks, pool_instructions),
compile_tasks.len() + pooled,
Expand Down Expand Up @@ -534,6 +535,7 @@ fn compile_scheduler_callees(
let max_blocks = sizes.iter().map(|size| size.0).max().unwrap_or(0);
let max_instructions = sizes.iter().map(|size| size.1).max().unwrap_or(0);
let workers = super::super::compile_resources::workers_with_state(
options.optimize_options.compile_threads(),
max_blocks,
max_instructions,
callees.len(),
Expand Down Expand Up @@ -642,6 +644,7 @@ fn compile_function_units(
let max_instructions = sizes.iter().map(|size| size.1).max().unwrap_or(0);
// Each worker compiles with a copy of the layout (below).
let workers = super::super::compile_resources::workers_with_state(
options.optimize_options.compile_threads(),
max_blocks,
max_instructions,
functions.len(),
Expand Down Expand Up @@ -807,6 +810,7 @@ fn compile_split_comb(
let mut order = (0..sizes.len()).collect::<Vec<_>>();
order.sort_by_key(|&index| std::cmp::Reverse(sizes[index]));
let workers = super::super::compile_resources::workers(
options.optimize_options.compile_threads(),
sizes.iter().map(|s| s.0).max().unwrap_or(0),
sizes.iter().map(|s| s.1).max().unwrap_or(0),
sizes.len(),
Expand Down Expand Up @@ -1093,6 +1097,7 @@ fn compile_remaining_processes(
);
}
let process_workers = super::super::compile_resources::workers(
options.optimize_options.compile_threads(),
max_process_blocks,
max_process_instructions,
process_sizes.len(),
Expand Down
1 change: 1 addition & 0 deletions crates/celox/src/backend/native/backend/lazy_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ impl Compiler {
(blocks.max(b), instructions.max(i))
});
super::super::compile_resources::workers_with_state(
self.options.optimize_options.compile_threads(),
blocks,
instructions,
functions.len(),
Expand Down
27 changes: 17 additions & 10 deletions crates/celox/src/backend/native/compile_resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,17 @@ const MIN_TASK_MEMORY: u64 = 128 * 1024 * 1024;
/// one worker.
const ASSUMED_BUDGET: u64 = 2 * 1024 * 1024 * 1024;

pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize {
workers_with_state(blocks, instructions, tasks, 0)
/// How many of `threads` (the compile threads of the options, see
/// `OptimizeOptions::compile_threads`) compile `tasks` tasks of at most
/// `blocks` blocks and `instructions` instructions.
pub(super) fn workers(threads: usize, blocks: usize, instructions: usize, tasks: usize) -> usize {
workers_with_state(threads, blocks, instructions, tasks, 0)
}

/// [`workers`] for tasks that each worker compiles with state of its own,
/// such as a copy of the layout, of `state` bytes.
pub(super) fn workers_with_state(
threads: usize,
blocks: usize,
instructions: usize,
tasks: usize,
Expand All @@ -59,12 +63,20 @@ pub(super) fn workers_with_state(
blocks,
instructions,
tasks,
std::thread::available_parallelism().map_or(1, usize::from),
cpus(threads),
available_memory(),
state,
)
}

/// The host threads compiling may use: `threads` of the options, no more
/// than the host has.
fn cpus(threads: usize) -> usize {
std::thread::available_parallelism()
.map_or(1, usize::from)
.min(threads.max(1))
}

/// About the heap a copy of `table` takes. A hash table holds a control byte
/// besides each entry.
fn table_bytes<K, V>(table: &fxhash::FxHashMap<K, V>) -> u64 {
Expand All @@ -91,17 +103,12 @@ pub(super) fn layout_bytes<A>(layout: &celox_state_layout::MemoryLayout<A>) -> u
/// 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(
threads: usize,
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(),
)
choose_workers_with_primary(primary, secondary, tasks, cpus(threads), available_memory())
}

fn choose_workers_with_primary(
Expand Down
Loading