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
2 changes: 1 addition & 1 deletion crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,7 @@ sizes partitioned search separately.

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`.
up to the available CPU cores and the partitioner's recommended partition count, `none` one thread, `{ count = n }` at most `n`.

### `PhaseConfig`

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 @@ -198,7 +198,8 @@ pub struct PartitionedSearchConfig {
pub partitioner: Option<String>,

/// Threads solving the partitions: `auto` runs one per partition up to the
/// available CPU cores, `none` runs one, and `{ count = n }` at most `n`.
/// available CPU cores and the partitioner's recommended partition count,
/// `none` runs one, and `{ count = n }` at most `n`.
#[serde(default)]
pub thread_count: MoveThreadCount,

Expand Down
4 changes: 2 additions & 2 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ Requires: `Send + Sync + Debug`. Bounds: `S: PlanningSolution`.
|--------|-----------|---------|
| `partition` | `fn(&self, solution: &S) -> Vec<S>` | — |
| `merge` | `fn(&self, original: &S, partitions: Vec<S>) -> S` | — |
| `recommended_partition_count` | `fn(&self) -> Option<usize>` | `None` |
| `recommended_partition_count` | `fn(&self) -> Option<NonZeroUsize>` | `None`; with `ThreadCount::Auto`, partitioned search runs at most this many threads |

### `CrossEntityDistanceMeter<S>` — `nearby_list_change.rs`

Expand Down Expand Up @@ -719,7 +719,7 @@ working solution without cloning.

**`FunctionalPartitioner<S, PF, MF>`** — Closure-based partitioner.

**`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.
**`ThreadCount`** — `resolve(partition_count, recommended)`. `Auto` (one thread per partition, at most one per available core and at most the partitioner's `recommended_partition_count`), `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.

**Configured `partitioned_search`** — The framework runs it; a search declaration only registers the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`, in a namespace separate from custom phase names. `partitioner = "name"` selects it. Each partition gets a director from `Director::fork_for_solution` over the partition and a `CompiledRuntimePhaseRunner` compiled from `partition_child_config`: the parent configuration with `child_phases` as its phases (empty means the default phases) and, as termination, the earliest of the solve's and the phase's time and step count limits, the bounds that reach a partition. The graph compiler compiles that child configuration once up front, so a child phase error fails the solve with a `phases[i].partitioned_search.child_phases[j]` path. The phase's `termination` becomes a `PartitionBound`: its time limit, counted from the phase's start, is shared by every partition, and its step count limit applies to each partition's solve (each partition counts its own steps; a bound inside a partition chains to the enclosing one, which also counts the inner steps). A partition that reaches the bound ends like a phase — `should_terminate` is true without a terminal reason and `solve_limit_reached` stays false — so its best solution is merged and the solve goes on to the next phase; a partition that starts after the deadline is merged as it was. Termination keys that need the merged solution's score (`best_score_limit`, `unimproved_step_count_limit`, `unimproved_seconds_spent_limit`) are rejected at compile time with their `phases[i].partitioned_search.termination.<key>` path. `thread_count` and `log_progress` apply as for `PartitionedSearchPhase` (`log_progress` logs `phase_start` with `partition_count` and `thread_count`, and `phase_end`). A child runner borrows its parent's `RuntimeGraphInput`, so nested partitioned phases compile to the same runner type. The `RuntimeExtensionRegistry` is `Send + Sync` for that reason: partition runners compile on the threads that solve them.

Expand Down
8 changes: 4 additions & 4 deletions crates/solverforge-solver/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ struct ExhaustiveSearchPhase: pub struct ExhaustiveSearchPhase<Dec> { /* private
ExhaustiveSearchPhase: pub fn phase_type_name(&self) -> &'static str
struct FunctionalPartitioner: pub struct FunctionalPartitioner<S, PF, MF> where S: PlanningSolution, PF: Fn(&S) -> Vec<S> + Send + Sync, MF: Fn(&S, Vec<S>) -> S + Send + Sync,{ /* private fields */ }
FunctionalPartitioner: pub fn new(partition_fn: PF, merge_fn: MF) -> Self
FunctionalPartitioner: pub fn with_recommended_count(self, count: usize) -> Self
FunctionalPartitioner: pub fn with_recommended_count(self, count: NonZeroUsize) -> Self
struct ListVariableMetadata: pub struct ListVariableMetadata<S, DM, IDM> { pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub route_get_fn: Option<fn(&S, usize) -> Vec<usize>>, pub route_set_fn: Option<fn(&mut S, usize, Vec<usize>)>, pub route_depot_fn: Option<fn(&S, usize) -> usize>, pub route_distance_fn: Option<fn(&S, usize, usize, usize) -> i64>, pub route_feasible_fn: Option<fn(&S, usize, &[usize]) -> bool>, pub savings_depot_fn: Option<fn(&S, usize) -> usize>, pub savings_metric_class_fn: Option<fn(&S, usize) -> usize>, pub savings_distance_fn: Option<fn(&S, usize, usize, usize) -> i64>, pub savings_feasible_fn: Option<fn(&S, usize, &[usize]) -> bool>, pub element_owner_fn: Option<fn(&S, &usize) -> Option<usize>>, /* private fields */ }
ListVariableMetadata: pub fn new( cross_distance_meter: DM, intra_distance_meter: IDM, route_get_fn: Option<fn(&S, usize) -> Vec<usize>>, route_set_fn: Option<fn(&mut S, usize, Vec<usize>)>, route_depot_fn: Option<fn(&S, usize) -> usize>, route_distance_fn: Option<fn(&S, usize, usize, usize) -> i64>, route_feasible_fn: Option<fn(&S, usize, &[usize]) -> bool>, savings_depot_fn: Option<fn(&S, usize) -> usize>, savings_metric_class_fn: Option<fn(&S, usize) -> usize>, savings_distance_fn: Option<fn(&S, usize, usize, usize) -> i64>, savings_feasible_fn: Option<fn(&S, usize, &[usize]) -> bool>, ) -> Self
ListVariableMetadata: pub fn with_element_owner_fn( self, element_owner_fn: Option<fn(&S, &usize) -> Option<usize>>, ) -> Self
Expand Down Expand Up @@ -563,7 +563,7 @@ enum SolverManagerError: pub enum SolverManagerError { NoFreeJobSlots, JobNotFou
enum SolverProgressKind: pub enum SolverProgressKind { Progress, BestSolution, }
enum SolverTerminalReason: pub enum SolverTerminalReason { Completed, TerminatedByConfig, Cancelled, Failed, }
enum ThreadCount: pub enum ThreadCount { Auto, Unlimited, Specific(NonZeroUsize), }
ThreadCount: pub fn resolve(&self, partition_count: usize) -> usize
ThreadCount: pub fn resolve( &self, partition_count: usize, recommended: Option<NonZeroUsize>, ) -> 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>), }
trait Acceptor: pub trait Acceptor<S: PlanningSolution>: Send + Debug { // Required method fn is_accepted( &mut self, last_step_score: &S::Score, move_score: &S::Score, move_signature: Option<&MoveTabuSignature>, ) -> bool; // Provided methods fn requires_move_signatures(&self) -> bool { ... } fn phase_started(&mut self, _initial_score: &S::Score) { ... } fn phase_ended(&mut self) { ... } fn step_started(&mut self) { ... } fn step_ended( &mut self, _step_score: &S::Score, _accepted_move_signature: Option<MoveTabuSignature>, ) { ... } }
Expand Down Expand Up @@ -656,10 +656,10 @@ trait ScoreBounder: pub trait ScoreBounder<S: PlanningSolution, D: Director<S>>:
ScoreBounder: fn calculate_pessimistic_bound(&self, score_director: &D) -> Option<S::Score>
trait Search: pub trait Search<S, V = usize, DM = DefaultCrossEntityDistanceMeter, IDM = DefaultCrossEntityDistanceMeter> where S: PlanningSolution + 'static, S::Score: Score + ParseableScore, V: Clone + Copy + PartialEq + Eq + Hash + Into<usize> + Send + Sync + Debug + 'static, DM: CrossEntityDistanceMeter<S> + Clone + Debug + Send + 'static, IDM: CrossEntityDistanceMeter<S> + Clone + Debug + Send + 'static,{ type Extensions: RuntimeExtensionRegistry<S, V, DM, IDM>; }
Search: type Extensions: RuntimeExtensionRegistry<S, V, DM, IDM>
trait SolutionPartitioner: pub trait SolutionPartitioner<S: PlanningSolution>: Send + Sync + Debug { // Required methods fn partition(&self, solution: &S) -> Vec<S>; fn merge(&self, original: &S, partitions: Vec<S>) -> S; // Provided method fn recommended_partition_count(&self) -> Option<usize> { ... } }
trait SolutionPartitioner: pub trait SolutionPartitioner<S: PlanningSolution>: Send + Sync + Debug { // Required methods fn partition(&self, solution: &S) -> Vec<S>; fn merge(&self, original: &S, partitions: Vec<S>) -> S; // Provided method fn recommended_partition_count(&self) -> Option<NonZeroUsize> { ... } }
SolutionPartitioner: fn partition(&self, solution: &S) -> Vec<S>
SolutionPartitioner: fn merge(&self, original: &S, partitions: Vec<S>) -> S
SolutionPartitioner: fn recommended_partition_count(&self) -> Option<usize>
SolutionPartitioner: fn recommended_partition_count(&self) -> Option<NonZeroUsize>
trait Solvable: pub trait Solvable: PlanningSolution + Send + 'static { // Required method fn solve( self, runtime: SolverRuntime<Self>, qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>, ) -> RuntimeBuildResult<()>; }
Solvable: fn solve( self, runtime: SolverRuntime<Self>, qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>, ) -> RuntimeBuildResult<()>
fn analyze: pub fn analyze<S>(solution: &S) -> ScoreAnalysis<S::Score> where S: Analyzable, S::Score: Score,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ where
}
}

fn recommended_partition_count(&self) -> Option<usize> {
fn recommended_partition_count(&self) -> Option<std::num::NonZeroUsize> {
match self {
Self::Previous(partitioner) => partitioner.recommended_partition_count(),
Self::Current(partitioner) => partitioner.recommended_partition_count(),
Expand Down
3 changes: 2 additions & 1 deletion crates/solverforge-solver/src/phase/partitioned/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ impl Default for PartitionedSearchConfig {

impl PartitionedSearchConfig {
/// Converts the TOML configuration: thread count `auto` is one thread per
/// partition up to the available CPU cores, `none` is one thread, and an
/// partition up to the available CPU cores and the partitioner's
/// recommended partition count, `none` is one thread, and an
/// explicit count is at most that many threads.
pub fn from_serialized(config: &solverforge_config::PartitionedSearchConfig) -> Self {
Self {
Expand Down
4 changes: 3 additions & 1 deletion crates/solverforge-solver/src/phase/partitioned/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ pub(crate) fn solve_partitioned<S, D, BestCb, PD, Part, MakeDirector, SolveChild
return;
}

let thread_count = config.thread_count.resolve(partition_count);
let thread_count = config
.thread_count
.resolve(partition_count, partitioner.recommended_partition_count());
if config.log_progress {
tracing::info!(
event = "phase_start",
Expand Down
38 changes: 17 additions & 21 deletions crates/solverforge-solver/src/phase/partitioned/partitioner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,10 @@ pub trait SolutionPartitioner<S: PlanningSolution>: Send + Sync + Debug {
/// The merged complete solution.
fn merge(&self, original: &S, partitions: Vec<S>) -> S;

/// Returns the recommended number of partitions.
///
/// This can be used by the partitioned search phase to determine
/// how many threads to use. Returns `None` if no recommendation.
fn recommended_partition_count(&self) -> Option<usize> {
/// The number of partitions worth solving at once, if this partitioner
/// knows it. With [`ThreadCount::Auto`], partitioned search runs at most
/// this many threads; an explicit thread count is unaffected.
fn recommended_partition_count(&self) -> Option<NonZeroUsize> {
None
}
}
Expand All @@ -75,7 +74,7 @@ where
{
partition_fn: PF,
merge_fn: MF,
recommended_count: Option<usize>,
recommended_count: Option<NonZeroUsize>,
_phantom: std::marker::PhantomData<fn() -> S>,
}

Expand All @@ -95,8 +94,9 @@ where
}
}

/// Sets the recommended partition count.
pub fn with_recommended_count(mut self, count: usize) -> Self {
/// Sets the recommended partition count (see
/// [`SolutionPartitioner::recommended_partition_count`]).
pub fn with_recommended_count(mut self, count: NonZeroUsize) -> Self {
self.recommended_count = Some(count);
self
}
Expand Down Expand Up @@ -129,15 +129,16 @@ where
(self.merge_fn)(original, partitions)
}

fn recommended_partition_count(&self) -> Option<usize> {
fn recommended_partition_count(&self) -> Option<NonZeroUsize> {
self.recommended_count
}
}

/// Thread count configuration for partitioned search.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThreadCount {
/// One thread per partition, at most one per available CPU core.
/// One thread per partition, at most one per available CPU core and at
/// most the partitioner's recommended partition count.
#[default]
Auto,
/// One thread per available CPU core.
Expand All @@ -147,22 +148,17 @@ pub enum ThreadCount {
}

impl ThreadCount {
/// Resolves the thread count to an actual number.
///
/// # Arguments
///
/// * `partition_count` - Number of partitions to process
///
/// # Returns
///
/// The number of threads to use.
pub fn resolve(&self, partition_count: usize) -> usize {
/// The number of threads that solve `partition_count` partitions, given
/// the partitioner's `recommended` partition count, which only bounds
/// [`ThreadCount::Auto`].
pub fn resolve(&self, partition_count: usize, recommended: Option<NonZeroUsize>) -> usize {
match self {
ThreadCount::Auto => {
let cpus = std::thread::available_parallelism()
.map(|p| p.get())
.unwrap_or(1);
std::cmp::min(cpus, partition_count)
let recommended = recommended.map_or(usize::MAX, NonZeroUsize::get);
cpus.min(partition_count).min(recommended)
}
ThreadCount::Unlimited => std::thread::available_parallelism()
.map(|p| p.get())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,34 @@ fn test_thread_count_display() {
#[test]
fn test_thread_count_resolve_specific() {
assert_eq!(
ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10),
ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10, None),
4
);
assert_eq!(
ThreadCount::Specific(std::num::NonZeroUsize::new(10).unwrap()).resolve(4),
ThreadCount::Specific(std::num::NonZeroUsize::new(10).unwrap()).resolve(4, None),
4
);
}

#[test]
fn test_thread_count_resolve_auto() {
let count = ThreadCount::Auto.resolve(100);
let count = ThreadCount::Auto.resolve(100, None);
assert!(count > 0);
}

#[test]
fn a_recommended_partition_count_bounds_only_auto() {
let two = std::num::NonZeroUsize::new(2);
let cores = std::thread::available_parallelism().map_or(1, |cores| cores.get());
assert_eq!(ThreadCount::Auto.resolve(100, two), cores.min(2));
assert_eq!(ThreadCount::Auto.resolve(1, two), 1);
assert_eq!(
ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10, two),
4
);
assert_eq!(ThreadCount::Unlimited.resolve(10, two), cores);
}

#[test]
fn test_functional_partitioner() {
let partitioner = FunctionalPartitioner::new(
Expand Down Expand Up @@ -103,7 +116,7 @@ fn test_partitioner_debug() {
|_: &TestSolution| Vec::new(),
|original: &TestSolution, _| original.clone(),
)
.with_recommended_count(4);
.with_recommended_count(std::num::NonZeroUsize::new(4).unwrap());

let debug = format!("{:?}", partitioner);
assert!(debug.contains("FunctionalPartitioner"));
Expand Down
32 changes: 32 additions & 0 deletions crates/solverforge/tests/partitioned_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,35 @@ fn the_phase_termination_ends_the_partitions_and_keeps_their_work() {
assert_eq!(records[0].task_ids, (0..8).collect::<Vec<_>>());
assert!(records[0].all_assigned);
}

const RECOMMENDED: &str = r#"
[[phases]]
type = "partitioned_search"
partitioner = "by_task_id_two_at_once"

[[phases.child_phases]]
type = "construction_heuristic"
construction_heuristic_type = "first_fit"

[[phases.child_phases]]
type = "custom"
name = "record"
"#;

#[test]
fn auto_threads_follow_the_recommended_partition_count() {
let solution = solve(Plan::new(RECOMMENDED));
assert!(solution
.tasks
.iter()
.all(|task| task.resource_idx.is_some()));

let records = take_records(RECOMMENDED);
assert_eq!(records.len(), 4);
let cores = std::thread::available_parallelism().map_or(1, |cores| cores.get());
let expected = cores.min(2);
if expected > 1 {
assert!(records.iter().all(|record| record.pool_threads == expected));
}
assert!(distinct_threads(&records) <= expected);
}
19 changes: 19 additions & 0 deletions crates/solverforge/tests/partitioned_search/domain/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ where
ctx.defaults()
.phase("record", |_| RecordPhase)
.partitioner("by_task_id", |_| ByTaskId)
.partitioner("by_task_id_two_at_once", |_| TwoAtOnce)
}

/// Splits the tasks by id modulo [`PARTITIONS`]; every partition keeps all
Expand Down Expand Up @@ -105,6 +106,24 @@ impl SolutionPartitioner<Plan> for ByTaskId {
}
}

/// [`ByTaskId`], recommending two partitions at once.
#[derive(Debug)]
struct TwoAtOnce;

impl SolutionPartitioner<Plan> for TwoAtOnce {
fn partition(&self, solution: &Plan) -> Vec<Plan> {
ByTaskId.partition(solution)
}

fn merge(&self, original: &Plan, partitions: Vec<Plan>) -> Plan {
ByTaskId.merge(original, partitions)
}

fn recommended_partition_count(&self) -> Option<std::num::NonZeroUsize> {
std::num::NonZeroUsize::new(2)
}
}

/// What the `record` child phase saw in one partition.
#[derive(Clone, Debug)]
pub struct Record {
Expand Down
Loading