Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
subsolver.h
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// Simple framework for choosing and distributing a solver "sub-tasks" on a set
15// of threads.
16
17#ifndef ORTOOLS_SAT_SUBSOLVER_H_
18#define ORTOOLS_SAT_SUBSOLVER_H_
19
20#include <algorithm>
21#include <cmath>
22#include <cstdint>
23#include <functional>
24#include <memory>
25#include <string>
26#include <utility>
27#include <vector>
28
29#include "absl/strings/string_view.h"
30#include "ortools/sat/util.h"
31#include "ortools/util/stats.h"
32
33#if !defined(__PORTABLE_PLATFORM__)
34#endif // __PORTABLE_PLATFORM__
35
36namespace operations_research {
37namespace sat {
38
39// The API used for distributing work. Each subsolver can generate tasks and
40// synchronize itself with the rest of the world.
41//
42// Note that currently only the main thread interact with subsolvers. Only the
43// tasks generated by GenerateTask() are executed in parallel in a threadpool.
44class SubSolver {
45 public:
47
48 SubSolver(absl::string_view name, SubsolverType type)
49 : name_(name), type_(type) {}
50 virtual ~SubSolver() = default;
51
52 // Synchronizes with the external world from this SubSolver point of view.
53 // Also incorporate the results of the latest completed tasks if any.
54 //
55 // Note(user): The intended implementation for determinism is that tasks
56 // update asynchronously (and so non-deterministically) global "shared"
57 // classes, but this global state is incorporated by the Subsolver only when
58 // Synchronize() is called.
59 //
60 // This is only called by the main thread in Subsolver creation order.
61 virtual void Synchronize() = 0;
62
63 // Returns true if this SubSolver is done and its memory can be freed. Note
64 // that the *Loop(subsolvers) functions below takes a reference in order to be
65 // able to clear the memory of a SubSolver as soon as it is done. Once this is
66 // true, the subsolver in question will be deleted and never used again.
67 //
68 // This is needed since some subsolve can be done before the overal Solve() is
69 // finished. This is the case for first solution subsolvers for instances.
70 //
71 // This is only called by the main thread in a sequential fashion.
72 // Important: This is only called when there is currently no task from that
73 // SubSolver in flight.
74 virtual bool IsDone() { return false; }
75
76 // Returns true iff GenerateTask() can be called.
77 // This is only called by the main thread in a sequential fashion.
78 virtual bool TaskIsAvailable() = 0;
79
80 // Returns a task to run. The task_id is just an ever increasing counter that
81 // correspond to the number of total calls to GenerateTask().
82 //
83 // TODO(user): We could use a more complex selection logic and pass in the
84 // deterministic time limit this subtask should run for. Unclear at this
85 // stage.
86 //
87 // This is only called by the main thread.
88 virtual std::function<void()> GenerateTask(int64_t task_id) = 0;
89
90 // Returns the total deterministic time spend by the completed tasks before
91 // the last Synchronize() call.
92 double deterministic_time() const { return deterministic_time_; }
93
94 // Returns the name of this SubSolver. Used in logs.
95 std::string name() const { return name_; }
96
97 // Returns the type of the subsolver.
98 SubsolverType type() const { return type_; }
99
100 // Note that this is protected by the global execution mutex and so it is
101 // called sequentially. Subclasses do not need to call this.
102 void AddTaskDuration(double duration_in_seconds) {
103 ++num_finished_tasks_;
104 duration_in_seconds = std::max(0.0, duration_in_seconds);
105 wall_time_ += duration_in_seconds;
106 timing_.AddTimeInSec(duration_in_seconds);
107 }
108
109 // Note that this is protected by the global execution mutex and so it is
110 // called sequentially. Subclasses do not need to call this.
111 void NotifySelection() { ++num_scheduled_tasks_; }
112
113 // This one need to be called by the Subclasses. Usually from Synchronize(),
114 // or from the task itself it we execute a single task at the same time.
115 void AddTaskDeterministicDuration(double deterministic_duration) {
116 if (deterministic_duration <= 0) return;
117 deterministic_time_ += deterministic_duration;
118 dtiming_.AddTimeInSec(deterministic_duration);
119 }
120
121 std::string TimingInfo() const {
122 // TODO(user): remove trailing "\n" from ValueAsString() or just build the
123 // table line directly.
124 std::string data = timing_.ValueAsString();
125 if (!data.empty()) data.pop_back();
126 return data;
127 }
128
129 std::string DeterministicTimingInfo() const {
130 // TODO(user): remove trailing "\n" from ValueAsString().
131 std::string data = dtiming_.ValueAsString();
132 if (!data.empty()) data.pop_back();
133 return data;
134 }
135
136 // Returns a score used to compare which tasks to schedule next.
137 // We will schedule the LOWER score.
138 //
139 // Tricky: Note that this will only be called sequentially. The deterministic
140 // time should only be used with the DeterministicLoop() because otherwise it
141 // can be updated at the same time as this is called.
142 double GetSelectionScore(bool deterministic) const {
143 const double time = deterministic ? deterministic_time_ : wall_time_;
144 const double divisor = num_scheduled_tasks_ > 0
145 ? static_cast<double>(num_scheduled_tasks_)
146 : 1.0;
147
148 // If we have little data, we strongly limit the number of task in flight.
149 // This is needed if some LNS are stuck for a long time to not just only
150 // schedule this type at the beginning.
151 const int64_t in_flight = num_scheduled_tasks_ - num_finished_tasks_;
152 const double confidence_factor =
153 num_finished_tasks_ > 10 ? 1.0 : std::exp(in_flight);
154
155 // We assume a "minimum time per task" which will be our base etimation for
156 // the average running time of this task.
157 return num_scheduled_tasks_ * std::max(0.1, time / divisor) *
158 confidence_factor;
159 }
160
161 private:
162 const std::string name_;
163 const SubsolverType type_;
164
165 int64_t num_scheduled_tasks_ = 0;
166 int64_t num_finished_tasks_ = 0;
167
168 // Sum of wall_time / deterministic_time.
169 double wall_time_ = 0.0;
170 double deterministic_time_ = 0.0;
171
172 TimeDistribution timing_ = TimeDistribution("task time");
173 TimeDistribution dtiming_ = TimeDistribution("task dtime");
174};
175
176// A simple wrapper to add a synchronization point in the list of subsolvers.
178 public:
179 explicit SynchronizationPoint(absl::string_view name, std::function<void()> f)
180 : SubSolver(name, HELPER), f_(std::move(f)) {}
181 bool TaskIsAvailable() final { return false; }
182 std::function<void()> GenerateTask(int64_t /*task_id*/) final {
183 return nullptr;
184 }
185 void Synchronize() final { f_(); }
186
187 private:
188 std::function<void()> f_;
189};
190
191// Executes the following loop:
192// 1/ Synchronize all in given order.
193// 2/ generate and schedule one task from the current "best" subsolver.
194// 3/ repeat until no extra task can be generated and all tasks are done.
195//
196// The complexity of each selection is in O(num_subsolvers), but that should
197// be okay given that we don't expect more than 100 such subsolvers.
198//
199// Note that it is okay to incorporate "special" subsolver that never produce
200// any tasks. This can be used to synchronize classes used by many subsolvers
201// just once for instance.
202void NonDeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
203 int num_threads, ModelSharedTimeLimit* time_limit);
204
205// Similar to NonDeterministicLoop() except this should result in a
206// deterministic solver provided that all SubSolver respect the Synchronize()
207// contract.
208//
209// Executes the following loop:
210// 1/ Synchronize all in given order.
211// 2/ generate and schedule up to batch_size tasks using an heuristic to select
212// which one to run.
213// 3/ wait for all task to finish.
214// 4/ repeat until no task can be generated in step 2.
215//
216// If max_num_batches is > 0, stop after that many batches.
217void DeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
218 int num_threads, int batch_size,
219 int max_num_batches = 0);
220
221// Same as above, but specialized implementation for the case num_threads=1.
222// This avoids using a Threadpool altogether. It should have the same behavior
223// than the functions above with num_threads=1 and batch_size=1. Note that an
224// higher batch size will not behave in the same way, even if num_threads=1.
225void SequentialLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers);
226
227} // namespace sat
228} // namespace operations_research
229
230#endif // ORTOOLS_SAT_SUBSOLVER_H_
SubSolver(absl::string_view name, SubsolverType type)
Definition subsolver.h:48
void AddTaskDeterministicDuration(double deterministic_duration)
Definition subsolver.h:115
std::string DeterministicTimingInfo() const
Definition subsolver.h:129
SubsolverType type() const
Definition subsolver.h:98
virtual std::function< void()> GenerateTask(int64_t task_id)=0
double GetSelectionScore(bool deterministic) const
Definition subsolver.h:142
void AddTaskDuration(double duration_in_seconds)
Definition subsolver.h:102
SynchronizationPoint(absl::string_view name, std::function< void()> f)
Definition subsolver.h:179
std::function< void()> GenerateTask(int64_t) final
Definition subsolver.h:182
void DeterministicLoop(std::vector< std::unique_ptr< SubSolver > > &subsolvers, int num_threads, int batch_size, int max_num_batches)
Definition subsolver.cc:130
void NonDeterministicLoop(std::vector< std::unique_ptr< SubSolver > > &subsolvers, const int num_threads, ModelSharedTimeLimit *time_limit)
Definition subsolver.cc:195
void SequentialLoop(std::vector< std::unique_ptr< SubSolver > > &subsolvers)
Definition subsolver.cc:97
OR-Tools root namespace.
STL namespace.