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: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 8 additions & 4 deletions crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }`.

Expand All @@ -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")]`.
Expand Down
3 changes: 2 additions & 1 deletion crates/solverforge-config/src/phase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ pub struct PartitionedSearchConfig {
/// Compile-time registered partitioner name.
pub partitioner: Option<String>,

/// 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,

Expand Down
11 changes: 8 additions & 3 deletions crates/solverforge-config/src/solver_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,16 +248,21 @@ 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,

/// No parallel move evaluation.
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.
Expand Down
17 changes: 16 additions & 1 deletion crates/solverforge-config/src/tests/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
10 changes: 6 additions & 4 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ src/
│ │ ├── phase.rs — LocalSearchPhase<S, M, MS, A, Fo>
│ │ ├── 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
Expand All @@ -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<S> trait
Expand Down Expand Up @@ -711,7 +713,7 @@ working solution without cloning.

**`FunctionalPartitioner<S, PF, MF>`** — 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

Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-solver/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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<S> { 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<S, V, DM, IDM> { Scalar(ScalarVariableSlot<S>), List(ListVariableSlot<S, V, DM, IDM>), DynamicScalar(DynamicScalarVariableSlot<S>), DynamicList(DynamicListVariableSlot<S>), }
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-solver/src/phase/localsearch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
119 changes: 119 additions & 0 deletions crates/solverforge-solver/src/phase/localsearch/parallel/auto.rs
Original file line number Diff line number Diff line change
@@ -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
}
}
40 changes: 33 additions & 7 deletions crates/solverforge-solver/src/phase/localsearch/parallel/config.rs
Original file line number Diff line number Diff line change
@@ -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),
},
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
16 changes: 12 additions & 4 deletions crates/solverforge-solver/src/phase/localsearch/parallel/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<BestCb>(&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<BestCb>(&mut self, solver_scope: &SolverScope<'_, S, D, BestCb>) -> bool
where
BestCb: ProgressCallback<S>,
{
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 {
Expand All @@ -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
Expand Down
Loading
Loading