Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
subsolver.cc
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
15
16#include <cstdint>
17#include <functional>
18#include <limits>
19#include <memory>
20#include <string>
21#include <utility>
22#include <vector>
23
24#include "absl/flags/flag.h"
25#include "absl/log/check.h"
26#include "absl/log/log.h"
27#include "absl/log/vlog_is_on.h"
28#include "absl/strings/str_cat.h"
29#include "absl/strings/str_join.h"
30#include "absl/strings/string_view.h"
31#include "absl/synchronization/blocking_counter.h"
32#include "absl/synchronization/mutex.h"
33#include "absl/time/clock.h"
34#include "absl/time/time.h"
35#include "absl/types/span.h"
37#include "ortools/base/timer.h"
38#include "ortools/sat/util.h"
39#if !defined(__PORTABLE_PLATFORM__)
41#endif // __PORTABLE_PLATFORM__
42
43namespace operations_research {
44namespace sat {
45
46namespace {
47
48// Returns the next SubSolver index from which to call GenerateTask(). Note that
49// only SubSolvers for which TaskIsAvailable() is true are considered. Return -1
50// if no SubSolver can generate a new task.
51//
52// For now we use a really basic logic that tries to equilibrate the walltime or
53// deterministic time spent in each subsolver.
54int NextSubsolverToSchedule(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
55 bool deterministic = true) {
56 int best = -1;
57 double best_score = std::numeric_limits<double>::infinity();
58 for (int i = 0; i < subsolvers.size(); ++i) {
59 if (subsolvers[i] == nullptr) continue;
60 if (subsolvers[i]->TaskIsAvailable()) {
61 const double score = subsolvers[i]->GetSelectionScore(deterministic);
62 if (best == -1 || score < best_score) {
63 best_score = score;
64 best = i;
65 }
66 }
67 }
68
69 if (best != -1) VLOG(1) << "Scheduling " << subsolvers[best]->name();
70 return best;
71}
72
73void ClearSubsolversThatAreDone(
74 absl::Span<const int> num_in_flight_per_subsolvers,
75 std::vector<std::unique_ptr<SubSolver>>& subsolvers) {
76 for (int i = 0; i < subsolvers.size(); ++i) {
77 if (subsolvers[i] == nullptr) continue;
78 if (num_in_flight_per_subsolvers[i] > 0) continue;
79 if (subsolvers[i]->IsDone()) {
80 // We can free the memory used by this solver for good.
81 VLOG(1) << "Deleting " << subsolvers[i]->name();
82 subsolvers[i].reset();
83 continue;
84 }
85 }
86}
87
88void SynchronizeAll(absl::Span<const std::unique_ptr<SubSolver>> subsolvers) {
89 for (const auto& subsolver : subsolvers) {
90 if (subsolver == nullptr) continue;
91 subsolver->Synchronize();
92 }
93}
94
95} // namespace
96
97void SequentialLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers) {
98 int64_t task_id = 0;
99 std::vector<int> num_in_flight_per_subsolvers(subsolvers.size(), 0);
100 while (true) {
101 SynchronizeAll(subsolvers);
102 ClearSubsolversThatAreDone(num_in_flight_per_subsolvers, subsolvers);
103 const int best = NextSubsolverToSchedule(subsolvers);
104 if (best == -1) break;
105 subsolvers[best]->NotifySelection();
106
107 WallTimer timer;
108 timer.Start();
109 subsolvers[best]->GenerateTask(task_id++)();
110 subsolvers[best]->AddTaskDuration(timer.Get());
111 }
112}
113
114#if defined(__PORTABLE_PLATFORM__)
115
116// On portable platform, we don't support multi-threading for now.
117
118void NonDeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
119 int num_threads, ModelSharedTimeLimit* time_limit) {
120 SequentialLoop(subsolvers);
121}
122
123void DeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
124 int num_threads, int batch_size, int max_num_batches) {
125 SequentialLoop(subsolvers);
126}
127
128#else // __PORTABLE_PLATFORM__
129
130void DeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
131 int num_threads, int batch_size, int max_num_batches) {
132 CHECK_GT(num_threads, 0);
133 CHECK_GT(batch_size, 0);
134 if (batch_size == 1) {
135 return SequentialLoop(subsolvers);
136 }
137
138 int64_t task_id = 0;
139 std::vector<int> num_in_flight_per_subsolvers(subsolvers.size(), 0);
140 std::vector<std::function<void()>> to_run;
141 std::vector<int> indices;
142 std::vector<double> timing;
143 to_run.reserve(batch_size);
144 ThreadPool pool(num_threads);
145 for (int batch_index = 0;; ++batch_index) {
146 VLOG(2) << "Starting deterministic batch of size " << batch_size;
147 SynchronizeAll(subsolvers);
148 ClearSubsolversThatAreDone(num_in_flight_per_subsolvers, subsolvers);
149
150 // We abort the loop after the last synchronize to properly reports final
151 // status in case max_num_batches is used.
152 if (max_num_batches > 0 && batch_index >= max_num_batches) break;
153
154 // We first generate all task to run in this batch.
155 // Note that we can't start the task right away since if a task finish
156 // before we schedule everything, we will not be deterministic.
157 to_run.clear();
158 indices.clear();
159 for (int t = 0; t < batch_size; ++t) {
160 const int best = NextSubsolverToSchedule(subsolvers);
161 if (best == -1) break;
162 num_in_flight_per_subsolvers[best]++;
163 subsolvers[best]->NotifySelection();
164 to_run.push_back(subsolvers[best]->GenerateTask(task_id++));
165 indices.push_back(best);
166 }
167 if (to_run.empty()) break;
168
169 // Schedule each task.
170 timing.resize(to_run.size());
171 absl::BlockingCounter blocking_counter(static_cast<int>(to_run.size()));
172 for (int i = 0; i < to_run.size(); ++i) {
173 pool.Schedule(
174 [i, f = std::move(to_run[i]), &timing, &blocking_counter]() {
175 WallTimer timer;
176 timer.Start();
177 f();
178 timing[i] = timer.Get();
179 blocking_counter.DecrementCount();
180 });
181 }
182
183 // Wait for all tasks of this batch to be done before scheduling another
184 // batch.
185 blocking_counter.Wait();
186
187 // Update times.
188 num_in_flight_per_subsolvers.assign(subsolvers.size(), 0);
189 for (int i = 0; i < to_run.size(); ++i) {
190 subsolvers[indices[i]]->AddTaskDuration(timing[i]);
191 }
192 }
193}
194
195void NonDeterministicLoop(std::vector<std::unique_ptr<SubSolver>>& subsolvers,
196 const int num_threads,
197 ModelSharedTimeLimit* time_limit) {
198 CHECK_GT(num_threads, 0);
199 if (num_threads == 1) {
200 return SequentialLoop(subsolvers);
201 }
202
203 // The mutex guards num_in_flight and num_in_flight_per_subsolvers.
204 // This is used to detect when the search is done.
205 absl::Mutex mutex;
206 int num_in_flight = 0; // Guarded by `mutex`.
207 std::vector<int> num_in_flight_per_subsolvers(subsolvers.size(), 0);
208
209 // Predicate to be used with absl::Condition to detect that num_in_flight <
210 // num_threads. Must only be called while locking `mutex`.
211 const auto num_in_flight_lt_num_threads = [&num_in_flight, num_threads]() {
212 return num_in_flight < num_threads;
213 };
214
215 ThreadPool pool(num_threads);
216
217 // The lambda below are using little space, but there is no reason
218 // to create millions of them, so we use the blocking nature of
219 // pool.Schedule() when the queue capacity is set.
220 int64_t task_id = 0;
221 while (true) {
222 // Set to true if no task is pending right now.
223 bool all_done = false;
224 {
225 // Wait if num_in_flight == num_threads.
226 const bool condition = mutex.LockWhenWithTimeout(
227 absl::Condition(&num_in_flight_lt_num_threads),
228 absl::Milliseconds(100));
229
230 // To support some "advanced" cancelation of subsolve, we still call
231 // synchronize every 0.1 seconds even if there is no worker available.
232 //
233 // TODO(user): We could also directly register callback to set stopping
234 // Boolean to false in a few places.
235 if (!condition) {
236 mutex.unlock();
237 SynchronizeAll(subsolvers);
238 continue;
239 }
240
241 // The stopping condition is that we do not have anything else to generate
242 // once all the task are done and synchronized.
243 if (num_in_flight == 0) all_done = true;
244 mutex.unlock();
245 }
246
247 SynchronizeAll(subsolvers);
248 int best = -1;
249 {
250 // We need to do that while holding the lock since substask below might
251 // be currently updating the time via AddTaskDuration().
252 const absl::MutexLock mutex_lock(mutex);
253 ClearSubsolversThatAreDone(num_in_flight_per_subsolvers, subsolvers);
254 best = NextSubsolverToSchedule(subsolvers, /*deterministic=*/false);
255 if (VLOG_IS_ON(1) && time_limit->LimitReached()) {
256 std::vector<std::string> debug;
257 for (int i = 0; i < subsolvers.size(); ++i) {
258 if (subsolvers[i] != nullptr && num_in_flight_per_subsolvers[i] > 0) {
259 debug.push_back(absl::StrCat(subsolvers[i]->name(), ":",
260 num_in_flight_per_subsolvers[i]));
261 }
262 }
263 if (!debug.empty()) {
264 VLOG_EVERY_N_SEC(1, 1)
265 << "Subsolvers still running after time limit: "
266 << absl::StrJoin(debug, ",");
267 }
268 }
269 }
270 if (best == -1) {
271 if (all_done) break;
272
273 // It is hard to know when new info will allows for more task to be
274 // scheduled, so for now we just sleep for a bit. Note that in practice We
275 // will never reach here except at the end of the search because we can
276 // always schedule LNS threads.
277 absl::SleepFor(absl::Milliseconds(1));
278 continue;
279 }
280
281 // Schedule next task.
282 subsolvers[best]->NotifySelection();
283 {
284 absl::MutexLock mutex_lock(mutex);
285 num_in_flight++;
286 num_in_flight_per_subsolvers[best]++;
287 }
288 std::function<void()> task = subsolvers[best]->GenerateTask(task_id++);
289 const std::string name = subsolvers[best]->name();
290 pool.Schedule([task = std::move(task), name, best, &subsolvers, &mutex,
291 &num_in_flight, &num_in_flight_per_subsolvers]() {
292 WallTimer timer;
293 timer.Start();
294 task();
295
296 const absl::MutexLock mutex_lock(mutex);
297 DCHECK(subsolvers[best] != nullptr);
298 DCHECK_GT(num_in_flight_per_subsolvers[best], 0);
299 num_in_flight_per_subsolvers[best]--;
300 VLOG(1) << name << " done in " << timer.Get() << "s.";
301 subsolvers[best]->AddTaskDuration(timer.Get());
302 num_in_flight--;
303 });
304 }
305}
306
307#endif // __PORTABLE_PLATFORM__
308
309} // namespace sat
310} // namespace operations_research
double Get() const
Definition timer.h:44
void Start()
Definition timer.h:30
void Schedule(absl::AnyInvocable< void() && > callback)
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.