diff --git a/README.md b/README.md index e4b7d3ef..da088c35 100644 --- a/README.md +++ b/README.md @@ -881,8 +881,10 @@ Local search can evaluate candidates on several cores within one solve: solverforge-py use `{"move_thread_count": {"count": 4}}`) runs each step's trials on up to four evaluators while one coordinator keeps the same acceptance order. The count is bounded by the solve's Rayon threads and by 32, -the size of one evaluation window. Results are reproducible at fixed work, and -the default (`auto`) currently stays sequential. +the size of one evaluation window. Results are reproducible at fixed work. The +default, `auto`, uses up to four evaluators and decides per step from measured +costs whether parallel windows are faster than sequential evaluation; the +result is the same either way. Absolute throughput depends on the model, constraints, neighborhood, hardware, and termination policy. Use emitted generated/evaluated throughput for one run diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index a10c7b42..0ebfcb52 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -744,9 +744,9 @@ Derives: `Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize`. | Variant | Note | |---------|------| -| `Auto` | **Default.** Sequential until benchmarks set an automatic policy | +| `Auto` | **Default.** Per step, sequential or parallel windows from measured costs | | `None` | Single-threaded | -| `Count(usize)` | Explicit count | +| `Count(NonZeroUsize)` | Explicit count; `{ count = 0 }` is rejected when the configuration is read | TOML: `move_thread_count = "auto"`, `"none"`, or `{ count = 4 }`. @@ -757,10 +757,14 @@ sizes partitioned search separately. | `move_thread_count` | Acceptor-forager local search | |---|---| | `None` | sequential | -| `Auto` | sequential | -| `Count(0)`, `Count(1)` | sequential | +| `Auto` | up to `min(4, rayon::current_num_threads())` evaluators; each step runs sequentially or in parallel windows, whichever its measured trial time, the previous step's candidate count, the calibrated fork-join cost of one window and the last replica rebuild say is faster, switching after 8 consecutive steps favour the other mode; sequential on a one-thread pool | +| `Count(1)` | sequential | | `Count(n >= 2)` | `min(n, rayon::current_num_threads(), 32)` evaluators: the main director plus that many minus one replicas; 32 is one full evaluation window | +Every policy reaches the sequential trajectory; `auto` changes speed only. +`PartitionedSearchConfig::thread_count`: `auto` runs one thread per partition +up to the available CPU cores, `none` one thread, `{ count = n }` at most `n`. + ### `PhaseConfig` Derives: `Debug, Clone, Deserialize, Serialize`. Tagged `#[serde(tag = "type", rename_all = "snake_case")]`. diff --git a/crates/solverforge-config/src/phase.rs b/crates/solverforge-config/src/phase.rs index 5ef8e857..e5d709cb 100644 --- a/crates/solverforge-config/src/phase.rs +++ b/crates/solverforge-config/src/phase.rs @@ -190,7 +190,8 @@ pub struct PartitionedSearchConfig { /// Compile-time registered partitioner name. pub partitioner: Option, - /// Thread count for child partitions. + /// Threads solving the partitions: `auto` runs one per partition up to the + /// available CPU cores, `none` runs one, and `{ count = n }` at most `n`. #[serde(default)] pub thread_count: MoveThreadCount, diff --git a/crates/solverforge-config/src/solver_config.rs b/crates/solverforge-config/src/solver_config.rs index e5ed322f..65a353f8 100644 --- a/crates/solverforge-config/src/solver_config.rs +++ b/crates/solverforge-config/src/solver_config.rs @@ -248,7 +248,11 @@ impl EnvironmentMode { #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum MoveThreadCount { - /// Sequential until benchmarks set an automatic policy. + /// Per step, sequential evaluation or parallel windows, whichever the + /// measured trial, window and replica costs say is faster; up to four + /// evaluators, bounded by the solve's Rayon threads. Results are the same + /// either way: parallel evaluation reaches the sequential trajectory. + /// Default. #[default] Auto, @@ -256,8 +260,9 @@ pub enum MoveThreadCount { None, /// Evaluator count, main director included; bounded by the solve's - /// Rayon threads and by one 32-candidate evaluation window. - Count(usize), + /// Rayon threads and by one 32-candidate evaluation window. Zero is + /// rejected when the configuration is read. + Count(NonZeroUsize), } /// Runtime configuration overrides. diff --git a/crates/solverforge-config/src/tests/parsing.rs b/crates/solverforge-config/src/tests/parsing.rs index 381addb3..fdd39e12 100644 --- a/crates/solverforge-config/src/tests/parsing.rs +++ b/crates/solverforge-config/src/tests/parsing.rs @@ -238,11 +238,26 @@ fn move_thread_count_parses_every_documented_form() { assert_eq!(parse("\"auto\""), MoveThreadCount::Auto); assert_eq!(parse("\"none\""), MoveThreadCount::None); - assert_eq!(parse("{ count = 4 }"), MoveThreadCount::Count(4)); + assert_eq!( + parse("{ count = 4 }"), + MoveThreadCount::Count(std::num::NonZeroUsize::new(4).unwrap()) + ); assert_eq!( SolverConfig::from_toml_str("").unwrap().move_thread_count, MoveThreadCount::Auto ); + + let zero = SolverConfig::from_toml_str("move_thread_count = { count = 0 }") + .expect_err("a zero evaluator count is rejected"); + assert!(zero.to_string().contains("nonzero"), "{zero}"); + let partitioned_zero = SolverConfig::from_toml_str( + "[[phases]]\ntype = \"partitioned_search\"\nthread_count = { count = 0 }\n", + ) + .expect_err("a zero partition thread count is rejected"); + assert!( + partitioned_zero.to_string().contains("nonzero"), + "{partitioned_zero}" + ); } #[test] diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 92252232..019b9613 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -253,7 +253,8 @@ src/ │ │ ├── phase.rs — LocalSearchPhase │ │ ├── phase/candidates.rs — Step candidate state and the parallel window loop │ │ ├── phase/decision.rs — Generated-candidate records and in-order candidate consumption for windows -│ │ ├── phase/evaluator.rs — Step evaluation strategy, selected once per phase: sequential loop or evaluator pool +│ │ ├── phase/adaptive.rs — AdaptiveEvaluator: the `auto` strategy, sequential or windows per step +│ │ ├── phase/evaluator.rs — Step evaluation strategy, selected once per phase: sequential loop, evaluator pool, or adaptive │ │ ├── phase/sequential.rs — One-evaluator candidate loop │ │ ├── phase/step.rs — One step: candidate selection and commit │ │ ├── phase/tests.rs — Tests @@ -262,11 +263,12 @@ src/ │ │ ├── forager/improving.rs — FirstBestScoreImprovingForager, FirstLastStepScoreImprovingForager │ │ ├── forager/tests.rs — Tests │ │ ├── parallel/mod.rs — Parallel evaluation module declarations +│ │ ├── parallel/auto.rs — AutoPolicy: the `auto` cost model, calibration and hysteresis │ │ ├── parallel/budget.rs — Remaining in-phase evaluation budget for window sizing -│ │ ├── parallel/config.rs — move_thread_count resolution to an evaluator count +│ │ ├── parallel/config.rs — move_thread_count resolution to an EvaluationPolicy │ │ ├── parallel/pool.rs — EvaluatorPool: evaluator replicas, sync, and post-commit advance │ │ ├── parallel/window.rs — Window evaluation across the main director and replicas -│ │ ├── parallel/tests/ — Pool ceiling, window sizing, trajectory parity, and allocation-free window tests +│ │ ├── parallel/tests/ — Pool ceiling, window sizing, auto policy, trajectory parity, and allocation-free window tests │ │ └── acceptor/ │ │ ├── mod.rs — Acceptor module declarations and re-exports │ │ ├── traits.rs — Acceptor trait @@ -711,7 +713,7 @@ working solution without cloning. **`FunctionalPartitioner`** — Closure-based partitioner. -**`ThreadCount`** — `Auto`, `Unlimited`, `Specific(usize)`. `PartitionedSearchPhase` solves child partitions sequentially when the resolved count is `1`, otherwise it installs a dedicated Rayon pool whose worker count matches the resolved value. +**`ThreadCount`** — `Auto` (one thread per partition, at most one per available core), `Unlimited` (one per available core), `Specific(NonZeroUsize)` (at most that many, at most one per partition). `PartitionedSearchPhase` solves child partitions sequentially when the resolved count is `1`, otherwise it installs a dedicated Rayon pool whose worker count matches the resolved value. ## Scope Hierarchy diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index b2b0465b..75752378 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -561,7 +561,7 @@ enum SolverLifecycleState: pub enum SolverLifecycleState { Solving, PauseRequest enum SolverManagerError: pub enum SolverManagerError { NoFreeJobSlots, JobNotFound { job_id: usize, }, InvalidStateTransition { job_id: usize, action: &'static str, state: SolverLifecycleState, }, NoSnapshotAvailable { job_id: usize, }, SnapshotNotFound { job_id: usize, snapshot_revision: u64, }, SnapshotAnalysisDisabled { job_id: usize, }, } enum SolverProgressKind: pub enum SolverProgressKind { Progress, BestSolution, } enum SolverTerminalReason: pub enum SolverTerminalReason { Completed, TerminatedByConfig, Cancelled, Failed, } -enum ThreadCount: pub enum ThreadCount { Auto, Unlimited, Specific(usize), } +enum ThreadCount: pub enum ThreadCount { Auto, Unlimited, Specific(NonZeroUsize), } ThreadCount: pub fn resolve(&self, partition_count: usize) -> usize enum ValueSource: pub enum ValueSource { Empty, CountableRange { from: usize, to: usize, }, SolutionCount { count_fn: fn(&S, usize) -> usize, provider_index: usize, }, EntitySlice { values_for_entity: for<'a> fn(&'a S, usize, usize) -> &'a [usize], }, } enum VariableSlot: pub enum VariableSlot { Scalar(ScalarVariableSlot), List(ListVariableSlot), DynamicScalar(DynamicScalarVariableSlot), DynamicList(DynamicListVariableSlot), } diff --git a/crates/solverforge-solver/src/phase/localsearch/mod.rs b/crates/solverforge-solver/src/phase/localsearch/mod.rs index a4271d1f..658da7b3 100644 --- a/crates/solverforge-solver/src/phase/localsearch/mod.rs +++ b/crates/solverforge-solver/src/phase/localsearch/mod.rs @@ -24,6 +24,6 @@ pub(crate) use forager::{ AcceptedCountForager, BestScoreForager, FirstAcceptedForager, FirstBestScoreImprovingForager, FirstLastStepScoreImprovingForager, ForagerDecision, LocalSearchForager, }; -pub(crate) use parallel::resolve_evaluator_count; +pub(crate) use parallel::{resolve_evaluation_policy, EvaluationPolicy}; pub(crate) use phase::solve_local_search_with_resources; pub(crate) use phase::LocalSearchPhase; diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/auto.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/auto.rs new file mode 100644 index 00000000..9251b761 --- /dev/null +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/auto.rs @@ -0,0 +1,119 @@ +//! The `move_thread_count = "auto"` policy: per step, sequential evaluation +//! or parallel windows, whichever the measured costs say is faster. +//! +//! Sequential and parallel evaluation reach identical trajectories, so the +//! policy changes how fast a step runs, never which move it selects. + +use std::hint::black_box; +use std::time::{Duration, Instant}; + +use rayon::prelude::*; + +use super::pool::MAX_PARALLEL_EVALUATION_WINDOW; + +/// Consecutive steps that must favour the other mode before the policy +/// switches, so one noisy step never triggers a replica rebuild. +pub(crate) const AUTO_SWITCH_STREAK: u32 = 8; + +/// Fork-join round trips timed when the policy calibrates; the fastest one is +/// the window overhead. +const CALIBRATION_ROUNDS: usize = 16; + +/// The cost model and switching state of one `auto` local-search phase. +#[derive(Debug)] +pub(crate) struct AutoPolicy { + evaluators: usize, + window_overhead: Duration, + parallel: bool, + streak: u32, + streak_saving_nanos: i128, + replica_build: Duration, +} + +impl AutoPolicy { + /// A sequential policy for `evaluators` evaluators (main director + /// included) whose windows cost `window_overhead` to fork and join. + pub(crate) fn new(evaluators: usize, window_overhead: Duration) -> Self { + Self { + evaluators: evaluators.clamp(1, MAX_PARALLEL_EVALUATION_WINDOW), + window_overhead, + parallel: false, + streak: 0, + streak_saving_nanos: 0, + replica_build: Duration::ZERO, + } + } + + /// Times an empty fork-join across `evaluators` on the current Rayon pool. + pub(crate) fn calibrate(evaluators: usize) -> Self { + let mut fastest = Duration::MAX; + for _ in 0..CALIBRATION_ROUNDS { + let started = Instant::now(); + rayon::join( + || black_box(0usize), + || { + (1..evaluators.max(1)) + .into_par_iter() + .for_each(|evaluator| { + black_box(evaluator); + }) + }, + ); + fastest = fastest.min(started.elapsed()); + } + Self::new(evaluators, fastest) + } + + /// Whether the next step runs parallel windows. + pub(crate) fn is_parallel(&self) -> bool { + self.parallel + } + + /// Records what building the replicas cost; the next switch to parallel + /// must be expected to win that back. + pub(crate) fn record_replica_build(&mut self, elapsed: Duration) { + self.replica_build = elapsed; + } + + /// Feeds one finished step: `consumed` candidates whose trials took + /// `trial_time` in total. Returns whether the next step runs parallel. + pub(crate) fn observe_step(&mut self, consumed: u64, trial_time: Duration) -> bool { + if self.evaluators <= 1 || consumed == 0 { + return self.parallel; + } + let saving = self.parallel_saving_nanos(consumed, trial_time); + let favours_parallel = saving > 0; + if favours_parallel == self.parallel { + self.streak = 0; + self.streak_saving_nanos = 0; + return self.parallel; + } + self.streak += 1; + self.streak_saving_nanos += saving; + let switching_to_parallel_pays = + self.streak_saving_nanos >= self.replica_build.as_nanos() as i128; + if self.streak >= AUTO_SWITCH_STREAK && (self.parallel || switching_to_parallel_pays) { + self.parallel = !self.parallel; + self.streak = 0; + self.streak_saving_nanos = 0; + } + self.parallel + } + + /// Expected nanoseconds one step like the observed one saves in parallel + /// windows; negative when sequential evaluation is faster. + /// + /// Sequential cost is the trial time. Parallel cost is one fork-join per + /// window plus the trials spread over the evaluators, including up to one + /// speculative trial per extra evaluator past the step's decision point. + pub(crate) fn parallel_saving_nanos(&self, consumed: u64, trial_time: Duration) -> i128 { + let consumed = i128::from(consumed.max(1)); + let evaluators = self.evaluators as i128; + let trial_nanos = trial_time.as_nanos() as i128; + let window = MAX_PARALLEL_EVALUATION_WINDOW as i128; + let windows = (consumed + window - 1) / window; + let parallel_trials = trial_nanos * (consumed + evaluators - 1) / (consumed * evaluators); + let parallel = windows * self.window_overhead.as_nanos() as i128 + parallel_trials; + trial_nanos - parallel + } +} diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/config.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/config.rs index 2d4d18ef..1bcbc71d 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/config.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/config.rs @@ -1,12 +1,38 @@ use solverforge_config::MoveThreadCount; -/// Number of evaluators (main director included) for acceptor-forager local -/// search. `Auto` stays sequential until benchmarks set its policy; an explicit -/// count is capped by the threads of the pool the solve runs on, and the -/// evaluator pool caps it again at one full window of candidates. -pub(crate) fn resolve_evaluator_count(count: &MoveThreadCount) -> usize { +/// Evaluators `move_thread_count = "auto"` uses at most, main director +/// included. Each evaluator beyond the main director holds a replica (a +/// working-solution clone with its own incremental score state), so `auto` +/// bounds the count to bound that memory; an explicit count can go higher. +pub(crate) const AUTO_MAX_EVALUATORS: usize = 4; + +/// How acceptor-forager local search evaluates each step's candidates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EvaluationPolicy { + /// The main director runs every trial. + Sequential, + /// Parallel windows across this many evaluators (at least two). + Fixed(usize), + /// Per step, sequential or parallel windows across up to this many + /// evaluators (at least two), chosen from measured costs. + Auto(usize), +} + +/// Resolves `move_thread_count` against the threads of the pool the solve +/// runs on: a pool of one thread is always sequential, and an explicit count +/// is capped at the pool's threads. The evaluator pool caps counts again at +/// one full window of candidates. +pub(crate) fn resolve_evaluation_policy(count: &MoveThreadCount) -> EvaluationPolicy { + let threads = rayon::current_num_threads().max(1); match count { - MoveThreadCount::Auto | MoveThreadCount::None => 1, - MoveThreadCount::Count(count) => (*count).clamp(1, rayon::current_num_threads().max(1)), + MoveThreadCount::None => EvaluationPolicy::Sequential, + MoveThreadCount::Count(count) => match count.get().min(threads) { + 1 => EvaluationPolicy::Sequential, + evaluators => EvaluationPolicy::Fixed(evaluators), + }, + MoveThreadCount::Auto => match threads.min(AUTO_MAX_EVALUATORS) { + 1 => EvaluationPolicy::Sequential, + evaluators => EvaluationPolicy::Auto(evaluators), + }, } } diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/mod.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/mod.rs index 3272cf4b..97169853 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/mod.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/mod.rs @@ -4,6 +4,7 @@ //! of candidates at a time; the coordinator consumes the results in candidate //! order through the unchanged acceptor and forager. +mod auto; mod budget; mod config; mod pool; @@ -12,7 +13,8 @@ mod window; #[cfg(test)] mod tests; +pub(crate) use auto::AutoPolicy; pub(crate) use budget::remaining_evaluation_budget; -pub(crate) use config::resolve_evaluator_count; +pub(crate) use config::{resolve_evaluation_policy, EvaluationPolicy}; pub(crate) use pool::{EvaluatorPool, MAX_PARALLEL_EVALUATION_WINDOW}; pub(crate) use window::evaluate_window; diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/pool.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/pool.rs index 1a490027..90e755db 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/pool.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/pool.rs @@ -130,15 +130,15 @@ where } /// Rebuilds the replicas when the working solution was written since they - /// last synced. Each replica clones the working solution once; this is the - /// evaluator replica clone boundary. - pub(crate) fn sync(&mut self, solver_scope: &SolverScope<'_, S, D, BestCb>) + /// last synced, and returns whether it did. Each replica clones the + /// working solution once; this is the evaluator replica clone boundary. + pub(crate) fn sync(&mut self, solver_scope: &SolverScope<'_, S, D, BestCb>) -> bool where BestCb: ProgressCallback, { let generation = solver_scope.working_solution_generation(); if self.evaluators <= 1 || self.synced_generation == Some(generation) { - return; + return false; } self.replicas.clear(); for _ in 1..self.evaluators { @@ -152,6 +152,14 @@ where }); } self.synced_generation = Some(generation); + true + } + + /// Drops the replicas, so the next `sync` rebuilds them. Steps evaluated + /// without the pool do not keep replicas at the committed solution. + pub(crate) fn release(&mut self) { + self.replicas.clear(); + self.synced_generation = None; } /// Applies the selected move to every replica by borrow, ahead of the diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/auto.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/auto.rs new file mode 100644 index 00000000..197503cc --- /dev/null +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/auto.rs @@ -0,0 +1,148 @@ +// The `auto` policy: its cost model, its switching, and that switching never +// changes the trajectory. + +use std::time::Duration; + +use super::super::auto::{AutoPolicy, AUTO_SWITCH_STREAK}; +use super::super::EvaluationPolicy; +use super::support::{fixed, forkable_director, run, selector, starting_solution, QueenMove}; +use crate::phase::localsearch::phase::{solve_local_search_with_evaluator, AdaptiveEvaluator}; +use crate::phase::localsearch::{AcceptedCountForager, HillClimbingAcceptor}; +use crate::scope::SolverScope; +use crate::test_utils::{create_nqueens_descriptor, NQueensSolution}; + +const MICRO: Duration = Duration::from_micros(1); + +#[test] +fn the_cost_model_weighs_trials_against_window_overhead() { + let policy = AutoPolicy::new(4, 10 * MICRO); + // 32 trials of 1 µs: 32 µs sequential; one 10 µs window plus 35 trials + // spread over 4 evaluators (8.75 µs) in parallel. + assert_eq!( + policy.parallel_saving_nanos(32, 32 * MICRO), + 32_000 - 18_750 + ); + // 4 trials of 1 µs cannot pay for one window. + assert!(policy.parallel_saving_nanos(4, 4 * MICRO) < 0); +} + +#[test] +fn expensive_steps_switch_to_parallel_after_a_streak() { + let mut policy = AutoPolicy::new(4, 10 * MICRO); + for _ in 1..AUTO_SWITCH_STREAK { + assert!(!policy.observe_step(32, 32 * MICRO * 100)); + } + assert!(policy.observe_step(32, 32 * MICRO * 100)); +} + +#[test] +fn cheap_steps_stay_sequential() { + let mut policy = AutoPolicy::new(4, 10 * MICRO); + for _ in 0..4 * AUTO_SWITCH_STREAK { + assert!(!policy.observe_step(4, 4 * MICRO)); + } +} + +#[test] +fn one_cheap_step_resets_the_streak() { + let mut policy = AutoPolicy::new(4, 10 * MICRO); + for _ in 1..AUTO_SWITCH_STREAK { + policy.observe_step(32, 3200 * MICRO); + } + assert!(!policy.observe_step(4, 4 * MICRO)); + for _ in 1..AUTO_SWITCH_STREAK { + assert!(!policy.observe_step(32, 3200 * MICRO)); + } + assert!(policy.observe_step(32, 3200 * MICRO)); +} + +#[test] +fn parallel_returns_to_sequential_when_steps_get_cheap() { + let mut policy = AutoPolicy::new(4, 10 * MICRO); + for _ in 0..AUTO_SWITCH_STREAK { + policy.observe_step(32, 3200 * MICRO); + } + assert!(policy.is_parallel()); + for _ in 1..AUTO_SWITCH_STREAK { + assert!(policy.observe_step(4, 4 * MICRO)); + } + assert!(!policy.observe_step(4, 4 * MICRO)); +} + +#[test] +fn switching_back_to_parallel_must_win_back_the_replica_rebuild() { + let mut policy = AutoPolicy::new(4, 10 * MICRO); + policy.record_replica_build(Duration::from_secs(1)); + // Each step saves about 2.3 ms; a streak saves about 18 ms, far less than + // the 1 s rebuild, so the policy keeps waiting. + for _ in 0..4 * AUTO_SWITCH_STREAK { + assert!(!policy.observe_step(32, 3200 * MICRO)); + } +} + +#[test] +fn a_single_evaluator_never_goes_parallel() { + let mut policy = AutoPolicy::new(1, Duration::ZERO); + for _ in 0..4 * AUTO_SWITCH_STREAK { + assert!(!policy.observe_step(32, Duration::from_secs(1))); + } +} + +/// Runs 25 hill-climbing steps with the `auto` evaluator under `policy` and +/// returns the final rows and whether the last step ran parallel windows. +fn run_auto(policy: AutoPolicy) -> (Vec>, bool) { + let descriptor = create_nqueens_descriptor(); + let mut solver_scope = + SolverScope::new(forkable_director!(starting_solution(), &descriptor)).with_seed(7); + solver_scope.start_solving(); + let mut source = selector(); + let mut acceptor = HillClimbingAcceptor::new(); + let mut forager = AcceptedCountForager::new(4, false); + let mut evaluator = AdaptiveEvaluator::::with_policy(4, policy); + solve_local_search_with_evaluator( + &mut source, + &mut (), + &mut acceptor, + &mut forager, + Some(25), + &mut evaluator, + &mut solver_scope, + ); + let rows = solver_scope + .working_solution() + .queens + .iter() + .map(|queen| queen.row) + .collect(); + (rows, evaluator.ran_parallel()) +} + +#[test] +fn auto_goes_parallel_on_free_windows_and_keeps_the_sequential_trajectory() { + let sequential = run(fixed(1), AcceptedCountForager::new(4, false), 25, None); + let (rows, parallel) = run_auto(AutoPolicy::new(4, Duration::ZERO)); + assert!(parallel, "free windows make every step favour parallel"); + assert_eq!(rows, sequential.rows); +} + +#[test] +fn auto_stays_sequential_on_costly_windows() { + let sequential = run(fixed(1), AcceptedCountForager::new(4, false), 25, None); + let (rows, parallel) = run_auto(AutoPolicy::new(4, Duration::from_secs(1))); + assert!(!parallel); + assert_eq!(rows, sequential.rows); +} + +#[test] +fn auto_with_a_calibrated_policy_keeps_the_sequential_trajectory() { + let sequential = run(fixed(1), AcceptedCountForager::new(4, false), 25, None); + let auto = run( + EvaluationPolicy::Auto(4), + AcceptedCountForager::new(4, false), + 25, + None, + ); + assert_eq!(auto.rows, sequential.rows); + assert_eq!(auto.score, sequential.score); + assert_eq!(auto.moves_evaluated, sequential.moves_evaluated); +} diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/mod.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/mod.rs index edc9fe1e..f41064d2 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/mod.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/mod.rs @@ -2,6 +2,7 @@ mod support; +mod auto; mod pool; mod sizing; mod trajectory; diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/sizing.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/sizing.rs index f63863b4..53f7dc6c 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/sizing.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/sizing.rs @@ -4,19 +4,61 @@ use crate::scope::SolverScope; use crate::test_utils::{create_nqueens_descriptor, NQueensSolution}; #[test] -fn evaluator_count_resolution() { +fn evaluation_policy_resolution() { + use std::num::NonZeroUsize; + use solverforge_config::MoveThreadCount; - use super::super::resolve_evaluator_count; + use super::super::config::AUTO_MAX_EVALUATORS; + use super::super::{resolve_evaluation_policy, EvaluationPolicy}; + + let count = |n: usize| MoveThreadCount::Count(NonZeroUsize::new(n).unwrap()); + let in_pool = |threads: usize, check: &(dyn Fn() + Sync)| { + rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .unwrap() + .install(check); + }; - assert_eq!(resolve_evaluator_count(&MoveThreadCount::None), 1); - assert_eq!(resolve_evaluator_count(&MoveThreadCount::Auto), 1); - assert_eq!(resolve_evaluator_count(&MoveThreadCount::Count(0)), 1); - assert_eq!(resolve_evaluator_count(&MoveThreadCount::Count(1)), 1); - assert_eq!( - resolve_evaluator_count(&MoveThreadCount::Count(2)), - 2.min(rayon::current_num_threads()) - ); + in_pool(8, &|| { + assert_eq!( + resolve_evaluation_policy(&MoveThreadCount::None), + EvaluationPolicy::Sequential + ); + assert_eq!( + resolve_evaluation_policy(&MoveThreadCount::Auto), + EvaluationPolicy::Auto(AUTO_MAX_EVALUATORS) + ); + assert_eq!( + resolve_evaluation_policy(&count(1)), + EvaluationPolicy::Sequential + ); + assert_eq!( + resolve_evaluation_policy(&count(6)), + EvaluationPolicy::Fixed(6) + ); + assert_eq!( + resolve_evaluation_policy(&count(64)), + EvaluationPolicy::Fixed(8) + ); + }); + in_pool(2, &|| { + assert_eq!( + resolve_evaluation_policy(&MoveThreadCount::Auto), + EvaluationPolicy::Auto(2) + ); + }); + in_pool(1, &|| { + assert_eq!( + resolve_evaluation_policy(&MoveThreadCount::Auto), + EvaluationPolicy::Sequential + ); + assert_eq!( + resolve_evaluation_policy(&count(4)), + EvaluationPolicy::Sequential + ); + }); } #[test] diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs index ff05029d..dca1cf07 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs @@ -8,6 +8,7 @@ use solverforge_scoring::IncrementalUniConstraint; use crate::heuristic::r#move::ChangeMove; use crate::heuristic::selector::move_selector::ChangeMoveSelector; +use crate::phase::localsearch::parallel::EvaluationPolicy; use crate::phase::localsearch::{ solve_local_search_with_resources, HillClimbingAcceptor, LocalSearchForager, SelectorCursorSource, @@ -94,8 +95,17 @@ pub(super) struct RunResult { pub(super) steps: u64, } +/// The policy of an explicit evaluator count: one evaluator is sequential. +pub(super) fn fixed(evaluators: usize) -> EvaluationPolicy { + if evaluators <= 1 { + EvaluationPolicy::Sequential + } else { + EvaluationPolicy::Fixed(evaluators) + } +} + pub(super) fn run( - evaluator_count: usize, + policy: EvaluationPolicy, mut forager: Fo, steps: u64, move_limit: Option, @@ -116,7 +126,7 @@ where &mut acceptor, &mut forager, Some(steps), - evaluator_count, + policy, &mut solver_scope, ); let stats = solver_scope.stats(); diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/trajectory.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/trajectory.rs index 0525e599..7fae5f0a 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/trajectory.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/trajectory.rs @@ -1,4 +1,4 @@ -use super::support::{forkable_director, run, selector, starting_solution}; +use super::support::{fixed, forkable_director, run, selector, starting_solution}; use crate::phase::localsearch::{ solve_local_search_with_resources, AcceptedCountForager, BestScoreForager, HillClimbingAcceptor, }; @@ -7,10 +7,10 @@ use crate::test_utils::{create_nqueens_descriptor, NQueensSolution}; #[test] fn sequential_and_parallel_reach_identical_trajectories() { - let sequential = run(1, AcceptedCountForager::new(4, false), 25, None); + let sequential = run(fixed(1), AcceptedCountForager::new(4, false), 25, None); for evaluator_count in [2, 4] { let parallel = run( - evaluator_count, + fixed(evaluator_count), AcceptedCountForager::new(4, false), 25, None, @@ -26,8 +26,8 @@ fn sequential_and_parallel_reach_identical_trajectories() { #[test] fn speculative_evaluations_are_reported_and_not_counted() { - let sequential = run(1, AcceptedCountForager::new(1, false), 10, None); - let parallel = run(2, AcceptedCountForager::new(1, false), 10, None); + let sequential = run(fixed(1), AcceptedCountForager::new(1, false), 10, None); + let parallel = run(fixed(2), AcceptedCountForager::new(1, false), 10, None); assert_eq!(parallel.rows, sequential.rows); assert_eq!(parallel.moves_evaluated, sequential.moves_evaluated); @@ -37,7 +37,7 @@ fn speculative_evaluations_are_reported_and_not_counted() { #[test] fn in_phase_move_limit_reserves_the_window() { - let parallel = run(2, BestScoreForager::new(false), 10, Some(5)); + let parallel = run(fixed(2), BestScoreForager::new(false), 10, Some(5)); assert_eq!(parallel.moves_evaluated, 5); assert_eq!(parallel.moves_speculative, 0); @@ -59,7 +59,7 @@ fn replicas_follow_solution_replacement() { &mut acceptor, &mut forager, Some(5), - evaluator_count, + fixed(evaluator_count), &mut solver_scope, ); solver_scope.replace_working_solution_and_reinitialize(NQueensSolution::with_rows(&[ @@ -71,7 +71,7 @@ fn replicas_follow_solution_replacement() { &mut acceptor, &mut forager, Some(5), - evaluator_count, + fixed(evaluator_count), &mut solver_scope, ); solver_scope @@ -87,8 +87,8 @@ fn replicas_follow_solution_replacement() { #[test] fn evaluator_counts_above_the_ceiling_keep_the_sequential_trajectory() { - let sequential = run(1, AcceptedCountForager::new(4, false), 25, None); - let parallel = run(64, AcceptedCountForager::new(4, false), 25, None); + let sequential = run(fixed(1), AcceptedCountForager::new(4, false), 25, None); + let parallel = run(fixed(64), AcceptedCountForager::new(4, false), 25, None); assert_eq!(parallel.rows, sequential.rows); assert_eq!(parallel.score, sequential.score); @@ -100,8 +100,8 @@ fn evaluator_counts_above_the_ceiling_keep_the_sequential_trajectory() { fn exhausted_move_budget_pulls_like_the_sequential_loop() { // A full-scan forager never discards speculative work, so generation // counts compare exactly, including the pull that meets the spent budget. - let sequential = run(1, BestScoreForager::new(false), 10, Some(5)); - let parallel = run(2, BestScoreForager::new(false), 10, Some(5)); + let sequential = run(fixed(1), BestScoreForager::new(false), 10, Some(5)); + let parallel = run(fixed(2), BestScoreForager::new(false), 10, Some(5)); assert_eq!(parallel.moves_evaluated, sequential.moves_evaluated); assert_eq!(parallel.moves_generated, sequential.moves_generated); diff --git a/crates/solverforge-solver/src/phase/localsearch/phase.rs b/crates/solverforge-solver/src/phase/localsearch/phase.rs index f2fe32f0..c490d81d 100644 --- a/crates/solverforge-solver/src/phase/localsearch/phase.rs +++ b/crates/solverforge-solver/src/phase/localsearch/phase.rs @@ -10,7 +10,7 @@ use tracing::info; use crate::heuristic::r#move::Move; use crate::heuristic::selector::move_selector::{CandidateId, MoveCandidateRef}; -use crate::phase::localsearch::parallel::EvaluatorPool; +use crate::phase::localsearch::parallel::{EvaluationPolicy, EvaluatorPool}; use crate::phase::localsearch::{ Acceptor, LocalSearchForager, MoveCursorSource, SelectorCursorSource, }; @@ -18,6 +18,7 @@ use crate::phase::Phase; use crate::scope::{PhaseScope, ProgressCallback, SolverScope}; use crate::stats::{format_duration, whole_units_per_second, CandidateTracePullToken}; +mod adaptive; mod candidates; mod decision; mod evaluator; @@ -26,6 +27,7 @@ mod step; pub(in crate::phase::localsearch) use decision::WindowSlot; +pub(crate) use adaptive::AdaptiveEvaluator; use evaluator::{SequentialEvaluator, StepEvaluator}; use step::{execute_step, StepOutcome}; @@ -239,9 +241,10 @@ where /// Executes the local-search phase while borrowing its resource only for /// cursor opening and individual candidate pulls. Both stock phases and the -/// compiled runtime call this function. The evaluator count selects the step -/// loop once, before the first step: one evaluator runs the sequential loop, -/// more run parallel windows across evaluator replicas. +/// compiled runtime call this function. The evaluation policy selects the +/// step loop once, before the first step: the sequential loop, parallel +/// windows across a fixed number of evaluator replicas, or the `auto` loop +/// that picks one of the two per step. #[allow(clippy::too_many_arguments)] pub(crate) fn solve_local_search_with_resources( move_source: &mut Source, @@ -249,7 +252,7 @@ pub(crate) fn solve_local_search_with_resources( acceptor: &mut A, forager: &mut Fo, step_limit: Option, - evaluator_count: usize, + policy: EvaluationPolicy, solver_scope: &mut SolverScope, ) where S: PlanningSolution, @@ -260,29 +263,70 @@ pub(crate) fn solve_local_search_with_resources( A: Acceptor, Fo: LocalSearchForager, { - if evaluator_count > 1 { - run_local_search( + match policy { + EvaluationPolicy::Sequential => run_local_search( move_source, resources, acceptor, forager, step_limit, - &mut EvaluatorPool::::new(evaluator_count), + &mut SequentialEvaluator, solver_scope, - ); - } else { - run_local_search( + ), + EvaluationPolicy::Fixed(evaluators) => run_local_search( move_source, resources, acceptor, forager, step_limit, - &mut SequentialEvaluator, + &mut EvaluatorPool::::new(evaluators), solver_scope, - ); + ), + EvaluationPolicy::Auto(evaluators) => run_local_search( + move_source, + resources, + acceptor, + forager, + step_limit, + &mut AdaptiveEvaluator::::new(evaluators), + solver_scope, + ), } } +/// Runs one phase with an explicit evaluator, so tests can drive the `auto` +/// evaluator with a fixed policy. +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +pub(crate) fn solve_local_search_with_evaluator( + move_source: &mut Source, + resources: &mut Source::Resources, + acceptor: &mut A, + forager: &mut Fo, + step_limit: Option, + evaluator: &mut E, + solver_scope: &mut SolverScope, +) where + S: PlanningSolution, + D: Director, + BestCb: ProgressCallback, + M: Move, + Source: MoveCursorSource + Debug + Send, + A: Acceptor, + Fo: LocalSearchForager, + E: StepEvaluator, +{ + run_local_search( + move_source, + resources, + acceptor, + forager, + step_limit, + evaluator, + solver_scope, + ); +} + #[allow(clippy::too_many_arguments)] fn run_local_search( move_source: &mut Source, @@ -397,7 +441,7 @@ where acceptor, forager, *step_limit, - 1, + EvaluationPolicy::Sequential, solver_scope, ); } diff --git a/crates/solverforge-solver/src/phase/localsearch/phase/adaptive.rs b/crates/solverforge-solver/src/phase/localsearch/phase/adaptive.rs new file mode 100644 index 00000000..141b3353 --- /dev/null +++ b/crates/solverforge-solver/src/phase/localsearch/phase/adaptive.rs @@ -0,0 +1,151 @@ +//! The `auto` evaluation strategy: each step runs sequentially or in parallel +//! windows, as the phase's [`AutoPolicy`] decides from measured costs. + +use std::time::Instant; + +use solverforge_core::domain::PlanningSolution; +use solverforge_scoring::Director; + +use crate::heuristic::r#move::Move; +use crate::heuristic::selector::move_selector::{MoveCandidateRef, ResourceMoveCursor}; +use crate::phase::localsearch::parallel::{AutoPolicy, EvaluatorPool}; +use crate::phase::localsearch::{Acceptor, LocalSearchForager}; +use crate::scope::{ProgressCallback, SolverScope, StepScope}; + +use super::candidates::{evaluate_candidate_windows, CandidateLoopState}; +use super::evaluator::StepEvaluator; +use super::sequential; + +/// An evaluator pool plus the policy that decides, step by step, whether to +/// use it. Leaving parallel mode releases the replicas; returning rebuilds them +/// at the committed solution, and the policy accounts for that rebuild. +pub(crate) struct AdaptiveEvaluator +where + S: PlanningSolution, + M: Move, +{ + pool: EvaluatorPool, + policy: AutoPolicy, + parallel_step: bool, +} + +impl AdaptiveEvaluator +where + S: PlanningSolution, + D: Director, + M: Move, +{ + /// Up to `evaluators` evaluators (main director included), starting + /// sequential, with a window overhead calibrated on the current pool. + pub(crate) fn new(evaluators: usize) -> Self { + Self::with_policy(evaluators, AutoPolicy::calibrate(evaluators)) + } + + pub(crate) fn with_policy(evaluators: usize, policy: AutoPolicy) -> Self { + Self { + pool: EvaluatorPool::new(evaluators), + policy, + parallel_step: false, + } + } + + /// Whether the last step ran in parallel windows. + #[cfg(test)] + pub(crate) fn ran_parallel(&self) -> bool { + self.parallel_step + } +} + +impl StepEvaluator for AdaptiveEvaluator +where + S: PlanningSolution, + D: Director, + M: Move, +{ + fn step_started(&mut self, solver_scope: &SolverScope<'_, S, D, BestCb>) + where + BestCb: ProgressCallback, + { + self.parallel_step = self.policy.is_parallel(); + if !self.parallel_step { + return; + } + let started = Instant::now(); + if self.pool.sync(solver_scope) { + self.policy.record_replica_build(started.elapsed()); + } + } + + fn evaluate_candidates( + &mut self, + cursor: &mut C, + resources: &mut Resources, + step_scope: &mut StepScope<'_, '_, '_, S, D, BestCb>, + last_step_score: S::Score, + acceptor: &mut A, + forager: &mut Fo, + requires_move_signatures: bool, + state: CandidateLoopState, + ) -> CandidateLoopState + where + BestCb: ProgressCallback, + C: ResourceMoveCursor, + A: Acceptor, + Fo: LocalSearchForager, + { + let consumed_before = state.evaluated_moves; + let trial_time_before = step_scope.phase_scope().stats().evaluation_time(); + let state = if self.parallel_step { + evaluate_candidate_windows( + cursor, + resources, + step_scope, + last_step_score, + acceptor, + forager, + requires_move_signatures, + &mut self.pool, + state, + ) + } else { + let state = sequential::evaluate_candidates( + cursor, + resources, + step_scope, + last_step_score, + acceptor, + forager, + requires_move_signatures, + state, + ); + // Keep the window target current for the first parallel step. + self.pool + .finish_step(state.evaluated_moves - consumed_before); + state + }; + let trial_time = step_scope + .phase_scope() + .stats() + .evaluation_time() + .saturating_sub(trial_time_before); + let next_parallel = self + .policy + .observe_step(state.evaluated_moves - consumed_before, trial_time); + if self.parallel_step && !next_parallel { + self.pool.release(); + } + state + } + + fn step_selected(&mut self, selected: &MoveCandidateRef<'_, S, M>, score: S::Score) { + if self.parallel_step { + self.pool.advance(selected, score); + } + } + + fn step_committed(&mut self, generation: u64) { + if self.parallel_step && self.policy.is_parallel() { + self.pool.mark_synced(generation); + } + } +} diff --git a/crates/solverforge-solver/src/phase/localsearch/phase/candidates.rs b/crates/solverforge-solver/src/phase/localsearch/phase/candidates.rs index 8ece37e0..c6aff29c 100644 --- a/crates/solverforge-solver/src/phase/localsearch/phase/candidates.rs +++ b/crates/solverforge-solver/src/phase/localsearch/phase/candidates.rs @@ -21,7 +21,7 @@ use super::decision::{ }; use super::StepMoveLabelCounts; -pub(super) struct CandidateLoopState { +pub(crate) struct CandidateLoopState { pub(super) interrupted: bool, pub(super) accepted_moves: u64, pub(super) generated_moves: u64, diff --git a/crates/solverforge-solver/src/phase/partitioned/config.rs b/crates/solverforge-solver/src/phase/partitioned/config.rs index aa0f72cf..bbc6dd8a 100644 --- a/crates/solverforge-solver/src/phase/partitioned/config.rs +++ b/crates/solverforge-solver/src/phase/partitioned/config.rs @@ -1,5 +1,7 @@ //! Partitioned search phase configuration. +use std::num::NonZeroUsize; + use solverforge_config::MoveThreadCount; use super::partitioner::ThreadCount; @@ -23,14 +25,15 @@ impl Default for PartitionedSearchConfig { } impl PartitionedSearchConfig { - /// Converts the TOML configuration: thread count `none` becomes one - /// thread and an explicit count is at least one. + /// Converts the TOML configuration: thread count `auto` is one thread per + /// partition up to the available CPU cores, `none` is one thread, and an + /// explicit count is at most that many threads. pub fn from_serialized(config: &solverforge_config::PartitionedSearchConfig) -> Self { Self { thread_count: match config.thread_count { MoveThreadCount::Auto => ThreadCount::Auto, - MoveThreadCount::None => ThreadCount::Specific(1), - MoveThreadCount::Count(count) => ThreadCount::Specific(count.max(1)), + MoveThreadCount::None => ThreadCount::Specific(NonZeroUsize::MIN), + MoveThreadCount::Count(count) => ThreadCount::Specific(count), }, log_progress: config.log_progress, } diff --git a/crates/solverforge-solver/src/phase/partitioned/mod.rs b/crates/solverforge-solver/src/phase/partitioned/mod.rs index 348c2e18..40f41ed1 100644 --- a/crates/solverforge-solver/src/phase/partitioned/mod.rs +++ b/crates/solverforge-solver/src/phase/partitioned/mod.rs @@ -15,7 +15,7 @@ Partitioned search splits a large problem into independent sub-problems use solverforge_solver::phase::partitioned::{PartitionedSearchConfig, ThreadCount}; let config = PartitionedSearchConfig { -thread_count: ThreadCount::Specific(4), +thread_count: ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()), log_progress: true, }; ``` diff --git a/crates/solverforge-solver/src/phase/partitioned/partitioner.rs b/crates/solverforge-solver/src/phase/partitioned/partitioner.rs index f743abc2..aac4ee66 100644 --- a/crates/solverforge-solver/src/phase/partitioned/partitioner.rs +++ b/crates/solverforge-solver/src/phase/partitioned/partitioner.rs @@ -4,6 +4,7 @@ //! solved independently (potentially in parallel), then merged back together. use std::fmt::Debug; +use std::num::NonZeroUsize; use solverforge_core::domain::PlanningSolution; @@ -136,13 +137,13 @@ where /// Thread count configuration for partitioned search. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ThreadCount { - /// Automatically determine based on available CPU cores. + /// One thread per partition, at most one per available CPU core. #[default] Auto, - /// Use all available CPU cores. + /// One thread per available CPU core. Unlimited, - /// Use a specific number of threads. - Specific(usize), + /// At most this many threads, and at most one per partition. + Specific(NonZeroUsize), } impl ThreadCount { @@ -166,7 +167,7 @@ impl ThreadCount { ThreadCount::Unlimited => std::thread::available_parallelism() .map(|p| p.get()) .unwrap_or(1), - ThreadCount::Specific(n) => std::cmp::min(*n, partition_count), + ThreadCount::Specific(n) => std::cmp::min(n.get(), partition_count), } } } diff --git a/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs b/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs index c03996ed..eebb291e 100644 --- a/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs +++ b/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs @@ -28,13 +28,25 @@ fn test_thread_count_default() { fn test_thread_count_display() { assert_eq!(format!("{}", ThreadCount::Auto), "Auto"); assert_eq!(format!("{}", ThreadCount::Unlimited), "Unlimited"); - assert_eq!(format!("{}", ThreadCount::Specific(4)), "4"); + assert_eq!( + format!( + "{}", + ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()) + ), + "4" + ); } #[test] fn test_thread_count_resolve_specific() { - assert_eq!(ThreadCount::Specific(4).resolve(10), 4); - assert_eq!(ThreadCount::Specific(10).resolve(4), 4); + assert_eq!( + ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10), + 4 + ); + assert_eq!( + ThreadCount::Specific(std::num::NonZeroUsize::new(10).unwrap()).resolve(4), + 4 + ); } #[test] diff --git a/crates/solverforge-solver/src/phase/partitioned/phase_tests.rs b/crates/solverforge-solver/src/phase/partitioned/phase_tests.rs index ade52fa9..dced39c7 100644 --- a/crates/solverforge-solver/src/phase/partitioned/phase_tests.rs +++ b/crates/solverforge-solver/src/phase/partitioned/phase_tests.rs @@ -395,7 +395,7 @@ fn partitioned_search_honors_specific_thread_count() { |_original, mut partitions| partitions.pop().unwrap(), ); let config = PartitionedSearchConfig { - thread_count: ThreadCount::Specific(2), + thread_count: ThreadCount::Specific(std::num::NonZeroUsize::new(2).unwrap()), log_progress: false, }; let mut phase = PartitionedSearchPhase::with_config( diff --git a/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs b/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs index 731c2396..676cf44b 100644 --- a/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs +++ b/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs @@ -19,7 +19,7 @@ fn sequential_partitioned_search_shares_step_limit_across_children() { |_original, mut partitions| partitions.pop().unwrap(), ); let config = PartitionedSearchConfig { - thread_count: ThreadCount::Specific(1), + thread_count: ThreadCount::Specific(std::num::NonZeroUsize::new(1).unwrap()), log_progress: false, }; let mut phase = PartitionedSearchPhase::with_config( @@ -62,7 +62,7 @@ fn sequential_partitioned_search_shares_move_limit_across_children() { |_original, mut partitions| partitions.pop().unwrap(), ); let config = PartitionedSearchConfig { - thread_count: ThreadCount::Specific(1), + thread_count: ThreadCount::Specific(std::num::NonZeroUsize::new(1).unwrap()), log_progress: false, }; let mut phase = PartitionedSearchPhase::with_config( @@ -105,7 +105,7 @@ fn sequential_partitioned_search_shares_score_limit_across_children() { |_original, mut partitions| partitions.pop().unwrap(), ); let config = PartitionedSearchConfig { - thread_count: ThreadCount::Specific(1), + thread_count: ThreadCount::Specific(std::num::NonZeroUsize::new(1).unwrap()), log_progress: false, }; let mut phase = PartitionedSearchPhase::with_config( diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs index 1521abe8..75880fd1 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs @@ -16,8 +16,8 @@ use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; use crate::phase::localsearch::vnd::solve_vnd_with_resources; use crate::phase::localsearch::{ solve_local_search_with_resources, AcceptedCountForager, BestScoreForager, - DiversifiedLateAcceptanceAcceptor, FirstLastStepScoreImprovingForager, LateAcceptanceAcceptor, - SimulatedAnnealingAcceptor, + DiversifiedLateAcceptanceAcceptor, EvaluationPolicy, FirstLastStepScoreImprovingForager, + LateAcceptanceAcceptor, SimulatedAnnealingAcceptor, }; use crate::runtime::compiler::{ DefaultLocalSearchAcceptorPolicy, DefaultLocalSearchComponents, DefaultLocalSearchForagerPolicy, @@ -46,7 +46,7 @@ where forager: Option, score_tie_break: ScoreTieBreak, random_seed: Option, - evaluator_count: usize, + evaluation_policy: EvaluationPolicy, }, VariableNeighborhoodDescent { phase_termination: Option, @@ -79,7 +79,7 @@ where forager, score_tie_break, random_seed, - evaluator_count, + evaluation_policy, } => { let (mut acceptor, mut forager) = build_acceptor_and_forager::( *components, @@ -96,7 +96,7 @@ where &mut acceptor, &mut forager, None, - *evaluator_count, + *evaluation_policy, solver_scope, ); }); diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/lowering.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/lowering.rs index 36412fa3..1a2ad518 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/lowering.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/lowering.rs @@ -11,7 +11,7 @@ use solverforge_core::domain::PlanningSolution; use solverforge_core::score::{ParseableScore, Score}; use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; -use crate::phase::localsearch::resolve_evaluator_count; +use crate::phase::localsearch::resolve_evaluation_policy; use crate::runtime::compiler::{ CompiledAcceptorForagerSelector, CompiledLocalSearch, CompiledRuntimeExtension, CompiledRuntimePhase, DefaultLocalSearchEligibility, DefaultRuntimeBindings, @@ -88,7 +88,7 @@ where forager: None, score_tie_break: solverforge_config::ScoreTieBreak::Random, random_seed: solver_config.resolved_random_seed(), - evaluator_count: resolve_evaluator_count( + evaluation_policy: resolve_evaluation_policy( &solver_config.move_thread_count, ), }), @@ -177,7 +177,7 @@ where forager, score_tie_break: config.score_tie_break, random_seed: solver_config.resolved_random_seed(), - evaluator_count: resolve_evaluator_count(&solver_config.move_thread_count), + evaluation_policy: resolve_evaluation_policy(&solver_config.move_thread_count), }, declaration, )) diff --git a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs index 36ee9807..d973b384 100644 --- a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs @@ -91,7 +91,7 @@ fn custom(name: &str) -> PhaseConfig { fn partitioned(name: Option<&str>) -> PhaseConfig { PhaseConfig::PartitionedSearch(PartitionedSearchConfig { partitioner: name.map(str::to_string), - thread_count: MoveThreadCount::Count(3), + thread_count: MoveThreadCount::Count(std::num::NonZeroUsize::new(3).unwrap()), log_progress: true, child_phases: vec![custom("child_extension")], termination: None, @@ -139,7 +139,10 @@ fn typed_extensions_lower_names_without_invoking_builders_and_freeze_config() { }; assert_eq!(name, "by_task"); assert_eq!(frozen.partitioner.as_deref(), Some("by_task")); - assert_eq!(frozen.thread_count, MoveThreadCount::Count(3)); + assert_eq!( + frozen.thread_count, + MoveThreadCount::Count(std::num::NonZeroUsize::new(3).unwrap()) + ); assert!(frozen.log_progress); assert_eq!(frozen.child_phases.len(), 1); @@ -149,7 +152,10 @@ fn typed_extensions_lower_names_without_invoking_builders_and_freeze_config() { live.partitioner = Some("mutated_after_compile".to_string()); live.thread_count = MoveThreadCount::None; assert_eq!(frozen.partitioner.as_deref(), Some("by_task")); - assert_eq!(frozen.thread_count, MoveThreadCount::Count(3)); + assert_eq!( + frozen.thread_count, + MoveThreadCount::Count(std::num::NonZeroUsize::new(3).unwrap()) + ); } #[test] diff --git a/crates/solverforge/tests/parallel_list_local_search/domain/plan.rs b/crates/solverforge/tests/parallel_list_local_search/domain/plan.rs index c21d761b..9fab009d 100644 --- a/crates/solverforge/tests/parallel_list_local_search/domain/plan.rs +++ b/crates/solverforge/tests/parallel_list_local_search/domain/plan.rs @@ -79,6 +79,8 @@ step_count_limit = 40 fn parallel_config(solution: &RoutePlan, _base: SolverConfig) -> SolverConfig { let mut config = SolverConfig::from_toml_str(PARALLEL_SOLVER_TOML) .expect("parallel list local-search fixture config must parse"); - config.move_thread_count = MoveThreadCount::Count(solution.move_threads); + config.move_thread_count = MoveThreadCount::Count( + std::num::NonZeroUsize::new(solution.move_threads).expect("a non-zero count"), + ); config } diff --git a/crates/solverforge/tests/parallel_local_search.rs b/crates/solverforge/tests/parallel_local_search.rs index f488bfc6..8f30e4ef 100644 --- a/crates/solverforge/tests/parallel_local_search.rs +++ b/crates/solverforge/tests/parallel_local_search.rs @@ -90,7 +90,8 @@ fn solve(manager: &'static SolverManager, move_threads: usize) -> Run { fn fixed_work_trajectory_is_identical_across_thread_counts() { static MANAGER: SolverManager = SolverManager::new(); - let runs: Vec<_> = [1, 2, 4] + // 0 runs `move_thread_count = "auto"`. + let runs: Vec<_> = [1, 2, 4, 0] .into_iter() .map(|move_threads| solve(&MANAGER, move_threads)) .collect(); @@ -134,8 +135,6 @@ fn fixed_work_trajectory_is_identical_across_thread_counts() { fn sequential_resolution_reports_no_speculation() { static MANAGER: SolverManager = SolverManager::new(); - for move_threads in [0, 1] { - let run = solve(&MANAGER, move_threads); - assert_eq!(run.telemetry.moves_speculative, 0); - } + let run = solve(&MANAGER, 1); + assert_eq!(run.telemetry.moves_speculative, 0); } diff --git a/crates/solverforge/tests/parallel_local_search/domain/plan.rs b/crates/solverforge/tests/parallel_local_search/domain/plan.rs index 7cfdc56d..40ca166c 100644 --- a/crates/solverforge/tests/parallel_local_search/domain/plan.rs +++ b/crates/solverforge/tests/parallel_local_search/domain/plan.rs @@ -59,7 +59,7 @@ fn parallel_config(solution: &Plan, _base: SolverConfig) -> SolverConfig { config.move_thread_count = if solution.move_threads == 0 { MoveThreadCount::Auto } else { - MoveThreadCount::Count(solution.move_threads) + MoveThreadCount::Count(std::num::NonZeroUsize::new(solution.move_threads).expect("a non-zero count")) }; config }