-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathwork_assignment.cc
More file actions
1514 lines (1441 loc) · 60.4 KB
/
work_assignment.cc
File metadata and controls
1514 lines (1441 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2025 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/work_assignment.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <deque>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/functional/function_ref.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "ortools/sat/clause.h"
#include "ortools/sat/cp_model_mapping.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_base.h"
#include "ortools/sat/integer_search.h"
#include "ortools/sat/lrat_proof_handler.h"
#include "ortools/sat/model.h"
#include "ortools/sat/restart.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_decision.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/synchronization.h"
#include "ortools/sat/util.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research::sat {
namespace {
const int kNumInitialRestarts = 10;
// If you build a tree by expanding the nodes with minimal depth+discrepancy,
// the number of leaves when all nodes less than a given value have been split
// follows the fibonacci sequence:
// num_leaves(0) := 1;
// num_leaves(1) := 2;
// num_leaves(n) := num_leaves(n-1) + num_leaves(n-2)
// This function returns f(n) := min({i | num_leaves(i) >= n})
int MaxAllowedDiscrepancyPlusDepth(int num_leaves) {
int i = 0;
int a = 1;
int b = 2;
while (a < num_leaves) {
std::tie(a, b) = std::make_pair(b, a + b);
++i;
}
return i;
}
// Returns the maximum depth of any leaf in the shared tree.
// This is an upper bound that can be computed without needing a lock on the
// shared tree.
int MaxPossibleLeafDepth(const SatParameters& params) {
const int num_leaves = params.shared_tree_open_leaves_per_worker() *
params.shared_tree_num_workers();
switch (params.shared_tree_split_strategy()) {
case SatParameters::SPLIT_STRATEGY_DISCREPANCY:
case SatParameters::SPLIT_STRATEGY_AUTO:
return MaxAllowedDiscrepancyPlusDepth(num_leaves) +
params.shared_tree_balance_tolerance();
case SatParameters::SPLIT_STRATEGY_BALANCED_TREE:
return std::ceil(std::log2(num_leaves)) +
params.shared_tree_balance_tolerance();
default:
return num_leaves;
}
}
} // namespace
Literal ProtoLiteral::Decode(CpModelMapping* mapping,
IntegerEncoder* encoder) const {
DCHECK_LT(proto_var_, mapping->NumProtoVariables());
if (mapping->IsBoolean(proto_var_)) {
return mapping->Literal(proto_var_);
}
return encoder->GetOrCreateAssociatedLiteral(DecodeInteger(mapping));
}
IntegerLiteral ProtoLiteral::DecodeInteger(CpModelMapping* mapping) const {
const int positive_var = PositiveRef(proto_var_);
if (!mapping->IsInteger(positive_var)) {
return IntegerLiteral();
}
if (proto_var_ < 0) {
return IntegerLiteral::LowerOrEqual(mapping->Integer(positive_var), -lb_);
}
return IntegerLiteral::GreaterOrEqual(mapping->Integer(positive_var), lb_);
}
std::optional<ProtoLiteral> ProtoLiteral::EncodeInteger(
IntegerLiteral literal, CpModelMapping* mapping) {
IntegerVariable positive_var = PositiveVariable(literal.var);
const int model_var =
mapping->GetProtoVariableFromIntegerVariable(positive_var);
if (model_var == -1) {
return std::nullopt;
}
ProtoLiteral result{
literal.var == positive_var ? model_var : NegatedRef(model_var),
literal.bound};
DCHECK_EQ(result.DecodeInteger(mapping), literal);
DCHECK_EQ(result.Negated().DecodeInteger(mapping), literal.Negated());
return result;
}
std::optional<ProtoLiteral> ProtoLiteral::Encode(Literal literal,
CpModelMapping* mapping,
IntegerEncoder* encoder) {
const std::optional<ProtoLiteral> result = EncodeLiteral(literal, mapping);
if (result.has_value()) return result;
for (auto int_lit : encoder->GetIntegerLiterals(literal)) {
auto result = EncodeInteger(int_lit, mapping);
if (result.has_value()) {
DCHECK_EQ(result->DecodeInteger(mapping), int_lit);
DCHECK_EQ(result->Negated().DecodeInteger(mapping), int_lit.Negated());
return result;
}
}
return std::nullopt;
}
std::optional<ProtoLiteral> ProtoLiteral::EncodeLiteral(
Literal literal, CpModelMapping* mapping) {
if (literal.Index() == kNoLiteralIndex) {
return std::nullopt;
}
int model_var =
mapping->GetProtoVariableFromBooleanVariable(literal.Variable());
if (model_var == -1) {
return std::nullopt;
}
DCHECK(mapping->IsBoolean(model_var));
ProtoLiteral result{literal.IsPositive() ? model_var : NegatedRef(model_var),
literal.IsPositive() ? 1 : 0};
return result;
}
namespace {
Literal DecodeWithIdentityMapping(const ProtoLiteral& literal) {
const int ref = literal.proto_var();
return Literal(BooleanVariable(PositiveRef(ref)), RefIsPositive(ref));
}
} // namespace
ProtoTrail::ProtoTrail() { target_phase_.reserve(kMaxPhaseSize); }
void ProtoTrail::PushLevel(const ProtoLiteral& decision,
IntegerValue objective_lb, int node_id) {
CHECK_GT(node_id, 0);
decision_indexes_.push_back(literals_.size());
assigned_at_level_[decision] = decision_indexes_.size();
literals_.push_back(decision);
node_ids_.push_back(node_id);
implications_.push_back({});
if (!level_to_objective_lbs_.empty()) {
objective_lb = std::max(level_to_objective_lbs_.back(), objective_lb);
}
level_to_objective_lbs_.push_back(objective_lb);
}
void ProtoTrail::SetLevelImplied(int level) {
DCHECK_GE(level, 1);
DCHECK_LE(level, decision_indexes_.size());
DCHECK_LE(level, implications_.size());
SetObjectiveLb(level - 1, ObjectiveLb(level));
const ProtoLiteral decision = Decision(level);
assigned_at_level_[decision] = level - 1;
// We don't store implications for level 0, so only move implications up to
// the parent if we are removing level 2 or greater.
if (level >= 2) {
MutableImplications(level - 1).push_back(decision);
}
for (const ProtoLiteral& implication : Implications(level)) {
assigned_at_level_[implication] = level - 1;
if (level >= 2) {
MutableImplications(level - 1).push_back(implication);
}
}
// implications_[level-1] stores the implications for level, which are now
// stored in the parent's implications, so we can delete them.
implications_.erase(implications_.begin() + level - 1);
decision_indexes_.erase(decision_indexes_.begin() + level - 1);
level_to_objective_lbs_.erase(level_to_objective_lbs_.begin() + level - 1);
}
void ProtoTrail::NormalizeImplications() {
assigned_at_level_.clear();
for (int level = 1; level <= MaxLevel(); ++level) {
assigned_at_level_[Decision(level)] = level;
int new_size = 0;
std::vector<ProtoLiteral>& implications = MutableImplications(level);
for (int i = 0; i < implications.size(); ++i) {
const ProtoLiteral& implication = implications[i];
if (!assigned_at_level_.contains(implication)) {
implications[new_size++] = implication;
assigned_at_level_[implication] = level;
}
}
implications.resize(new_size);
}
}
void ProtoTrail::Clear() {
decision_indexes_.clear();
literals_.clear();
level_to_objective_lbs_.clear();
node_ids_.clear();
target_phase_.clear();
assigned_at_level_.clear();
implications_.clear();
}
void ProtoTrail::SetObjectiveLb(int level, IntegerValue objective_lb) {
if (level == 0) return;
level_to_objective_lbs_[level - 1] =
std::max(objective_lb, level_to_objective_lbs_[level - 1]);
}
int ProtoTrail::DecisionNodeId(int level) const {
DCHECK_LE(level, decision_indexes_.size());
return node_ids_[decision_indexes_[level - 1]];
}
absl::Span<const int> ProtoTrail::NodeIds(int level) const {
DCHECK_LE(level, decision_indexes_.size());
int start = level == 0 ? 0 : decision_indexes_[level - 1];
int end = level == decision_indexes_.size() ? node_ids_.size()
: decision_indexes_[level];
return absl::MakeSpan(node_ids_.data() + start, end - start);
}
absl::Span<const ProtoLiteral> ProtoTrail::Implications(int level) const {
if (level > implications_.size() || level <= 0) {
return absl::MakeSpan(literals_.data(), 0);
}
return absl::MakeSpan(implications_[level - 1]);
}
SharedTreeManager::SharedTreeManager(Model* model)
: params_(*model->GetOrCreate<SatParameters>()),
num_workers_(std::max(0, params_.shared_tree_num_workers())),
max_path_depth_(MaxPossibleLeafDepth(params_)),
shared_response_manager_(model->GetOrCreate<SharedResponseManager>()),
lrat_proof_handler_(LratProofHandler::MaybeCreate(
params_, &clause_id_generator_,
model->GetOrCreate<SharedLratProofStatus>(),
model->GetOrCreate<SharedStatistics>())),
num_splits_wanted_(
num_workers_ * params_.shared_tree_open_leaves_per_worker() - 1),
max_nodes_(
params_.shared_tree_max_nodes_per_worker() >=
std::numeric_limits<int>::max() / std::max(num_workers_, 1)
? std::numeric_limits<int>::max()
: num_workers_ * params_.shared_tree_max_nodes_per_worker()) {
// Create the root node with a fake decision.
nodes_.push_back(
{.decision = ProtoLiteral(),
.objective_lb = shared_response_manager_->GetInnerObjectiveLowerBound(),
.trail_info = std::make_unique<NodeTrailInfo>()});
unassigned_leaves_.push_back(&nodes_.back());
}
int SharedTreeManager::NumNodes() const {
absl::MutexLock mutex_lock(mu_);
return nodes_.size();
}
bool SharedTreeManager::SyncTree(ProtoTrail& path) {
absl::MutexLock mutex_lock(mu_);
std::vector<std::pair<Node*, int>> nodes = GetAssignedNodes(path);
if (!IsValid(path)) {
path.Clear();
return false;
}
DCHECK(CheckLratInvariants());
// We don't rely on these being empty, but we expect them to be.
DCHECK(to_close_.empty());
DCHECK(to_update_.empty());
int prev_level = -1;
for (const auto& [node, level] : nodes) {
if (level == prev_level) {
// `node` is implied by the previous decisions in `path`, hence its
// sibling can be closed (using this implication as proof; the implication
// proved by the worker providing `path` must be imported and a new one,
// adapted for the manager, must be inferred from it).
Node* sibling = GetSibling(node);
ClauseId closing_clause_id = kNoClauseId;
if (lrat_proof_handler_ != nullptr) {
// For the worker, `node` is implied by all the previous decisions in
// `path`, but for the manager we need an implication clause using the
// non-implied ancestors of `node` in the tree (they can be different
// because the manager and the worker have different views of the tree).
const std::vector<Literal> inferred_clause = ClosingClause(sibling);
std::vector<Literal> imported_clause;
std::vector<ClauseId> lrat_proof;
for (int l = 1; l <= level + 1; ++l) {
Node* n = l <= level ? GetNode(path.DecisionNodeId(l)) : node;
const Literal decision = DecodeWithIdentityMapping(n->decision);
imported_clause.push_back(l <= level ? decision.Negated() : decision);
if (n->implied_and_processed) {
lrat_proof.push_back(GetSibling(n)->closing_clause_id);
}
}
closing_clause_id = AddImportedAndInferredClauses(
imported_clause, inferred_clause, lrat_proof);
}
to_close_.emplace_back(sibling, closing_clause_id);
} else if (level > 0 && node->objective_lb < path.ObjectiveLb(level)) {
node->objective_lb = path.ObjectiveLb(level);
to_update_.push_back(node->parent);
}
if (level > 0 && !node->closed) {
NodeTrailInfo* trail_info = GetTrailInfo(node);
for (const ProtoLiteral& implication : path.Implications(level)) {
// Trivial implication, can be ignored.
if (IsDecisionOfNodeOrAncestor(implication, node)) continue;
ClauseId implication_clause_id = kNoClauseId;
if (lrat_proof_handler_ != nullptr) {
// For the worker, 'implication' is implied by all the previous
// decisions in `path`, but for the manager we need an implication
// clause using the non-implied ancestors of `node` in the tree (they
// can be different because the manager and the worker have different
// views of the tree).
const std::vector<Literal> inferred_clause =
ImplicationClause(node, implication);
std::vector<Literal> imported_clause;
std::vector<ClauseId> lrat_proof;
for (int l = 1; l <= level; ++l) {
Node* n = GetNode(path.DecisionNodeId(l));
const Literal decision = DecodeWithIdentityMapping(n->decision);
imported_clause.push_back(decision.Negated());
if (n->implied_and_processed) {
lrat_proof.push_back(GetSibling(n)->closing_clause_id);
}
}
imported_clause.push_back(DecodeWithIdentityMapping(implication));
implication_clause_id = AddImportedAndInferredClauses(
imported_clause, inferred_clause, lrat_proof);
}
auto it = trail_info->implications
.emplace(implication.proto_var(),
std::make_pair(implication.lb(),
implication_clause_id))
.first;
if (it->second.first < implication.lb()) {
it->second.first = implication.lb();
}
}
}
prev_level = level;
}
ProcessNodeChanges();
if (nodes.back().first->closed) {
path.Clear();
return false;
}
// Restart after processing updates - we might learn a new objective bound.
// Do initial restarts once each worker has had the chance to be assigned a
// leaf.
if (num_leaves_assigned_since_restart_ >= num_workers_ &&
num_restarts_ < kNumInitialRestarts) {
RestartLockHeld();
path.Clear();
return false;
}
// Sync lower bounds and implications from the shared tree to `path`.
AssignLeaf(path, nodes.back().first);
DCHECK(CheckLratInvariants());
return true;
}
int SharedTreeManager::TrySplitTree(absl::Span<const ProtoLiteral> decisions,
ProtoTrail& path) {
decisions = decisions.subspan(0, max_path_depth_ - path.MaxLevel());
if (decisions.empty()) return 0;
absl::MutexLock l(mu_);
for (int i = 0; i < decisions.size(); ++i) {
if (!TrySplitTreeLockHeld(decisions[i], path)) return i;
}
return decisions.size();
}
bool SharedTreeManager::TrySplitTreeLockHeld(ProtoLiteral decision,
ProtoTrail& path) {
if (!IsValid(path)) return false;
std::vector<std::pair<Node*, int>> nodes = GetAssignedNodes(path);
if (nodes.back().first->closed) {
VLOG(2) << "Cannot split closed node";
return false;
}
if (nodes.back().first->children[0] != nullptr) {
LOG_IF(WARNING, nodes.size() > 1)
<< "Cannot resplit previously split node @ " << nodes.back().second
<< "/" << nodes.size();
return false;
}
if (nodes_.size() + 2 > max_nodes_) {
VLOG(2) << "Too many nodes to accept split";
return false;
}
if (num_splits_wanted_ <= 0) {
VLOG(2) << "Enough splits for now";
return false;
}
for (const auto& [node, level] : nodes) {
if (decision == node->decision || decision == node->decision.Negated()) {
VLOG(2) << "Cannot split on decision which is already in the tree";
return false;
}
}
if (params_.shared_tree_split_strategy() ==
SatParameters::SPLIT_STRATEGY_DISCREPANCY ||
params_.shared_tree_split_strategy() ==
SatParameters::SPLIT_STRATEGY_AUTO) {
int discrepancy = 0;
for (const auto& [node, level] : nodes) {
if (node->parent == nullptr || node->implied) continue;
IntegerValue sibling_bound = GetSibling(node)->objective_lb;
discrepancy += (node->objective_lb == sibling_bound
? node != node->parent->children[0]
: node->objective_lb > sibling_bound);
}
// TODO(user): Need to write up the shape this creates.
// This rule will allow twice as many leaves in the preferred subtree.
if (discrepancy + path.MaxLevel() >= max_path_depth_) {
VLOG(2) << "Too high discrepancy to accept split";
return false;
}
} else if (params_.shared_tree_split_strategy() ==
SatParameters::SPLIT_STRATEGY_OBJECTIVE_LB) {
if (nodes.back().first->objective_lb > nodes.front().first->objective_lb) {
VLOG(2) << "Can only split nodes with minimum objective lb, "
<< nodes.back().first->objective_lb << " > "
<< nodes.front().first->objective_lb;
return false;
}
}
VLOG_EVERY_N(2, 10) << unassigned_leaves_.size() << " unassigned leaves, "
<< nodes_.size() << " subtrees, " << num_splits_wanted_
<< " splits wanted";
Split(nodes, decision);
auto [new_leaf, level] = nodes.back();
path.PushLevel(new_leaf->decision, new_leaf->objective_lb, new_leaf->id);
return true;
}
void SharedTreeManager::ReplaceTree(ProtoTrail& path) {
absl::MutexLock mutex_lock(mu_);
std::vector<std::pair<Node*, int>> nodes = GetAssignedNodes(path);
if (nodes.back().first->children[0] == nullptr &&
!nodes.back().first->closed && nodes.size() > 1) {
Node* leaf = nodes.back().first;
VLOG(2) << "Returning leaf to be replaced";
GetTrailInfo(leaf)->phase = path.TakeTargetPhase();
unassigned_leaves_.push_back(leaf);
}
path.Clear();
while (!unassigned_leaves_.empty()) {
Node* leaf = unassigned_leaves_.front();
unassigned_leaves_.pop_front();
if (!leaf->closed && leaf->children[0] == nullptr) {
num_leaves_assigned_since_restart_ += 1;
AssignLeaf(path, leaf);
path.SetTargetPhase(std::move(GetTrailInfo(leaf)->phase));
return;
}
}
VLOG(2) << "Assigning root because no unassigned leaves are available";
// TODO(user): Investigate assigning a random leaf so workers can still
// improve shared tree bounds.
}
SharedTreeManager::NodeTrailInfo* SharedTreeManager::GetTrailInfo(Node* node) {
CHECK(node != nullptr && !node->closed);
while (node->trail_info == nullptr) {
node = node->parent;
}
CHECK_NE(node, nullptr);
return node->trail_info.get();
}
void SharedTreeManager::ClearTrailInfo(Node* node, bool implications_only) {
if (node->trail_info == nullptr) return;
if (lrat_proof_handler_ != nullptr) {
for (const auto& [var, lb_and_clause] : node->trail_info->implications) {
lrat_proof_handler_->DeleteClause(lb_and_clause.second, {});
}
}
if (implications_only) {
node->trail_info->implications.clear();
} else {
node->trail_info.reset();
}
}
SharedTreeManager::Node* SharedTreeManager::GetSibling(const Node* node) const {
if (node == nullptr || node->parent == nullptr) return nullptr;
if (node->parent->children[0] != node) {
return node->parent->children[0];
}
return node->parent->children[1];
}
void SharedTreeManager::Split(std::vector<std::pair<Node*, int>>& nodes,
ProtoLiteral lit) {
const auto [parent, level] = nodes.back();
DCHECK(parent->children[0] == nullptr);
DCHECK(parent->children[1] == nullptr);
parent->children[0] = MakeSubtree(parent, lit);
parent->children[1] = MakeSubtree(parent, lit.Negated());
NodeTrailInfo* trail_info = GetTrailInfo(parent);
if (trail_info != nullptr) {
parent->children[0]->trail_info =
std::make_unique<NodeTrailInfo>(NodeTrailInfo{});
parent->children[1]->trail_info = std::make_unique<NodeTrailInfo>(
NodeTrailInfo{.phase = std::move(trail_info->phase)});
}
nodes.push_back(std::make_pair(parent->children[0], level + 1));
unassigned_leaves_.push_back(parent->children[1]);
--num_splits_wanted_;
}
SharedTreeManager::Node* SharedTreeManager::MakeSubtree(Node* parent,
ProtoLiteral decision) {
nodes_.push_back(
Node{.decision = decision,
.objective_lb = parent->objective_lb,
.parent = parent,
.id = static_cast<int>(nodes_.size() + node_id_offset_)});
return &nodes_.back();
}
void SharedTreeManager::ProcessNodeChanges() {
DCHECK(CheckLratInvariants());
int num_newly_closed = 0;
std::vector<Node*> newly_implied;
while (!to_close_.empty()) {
auto [node, closing_clause_id] = to_close_.back();
CHECK_NE(node, nullptr);
to_close_.pop_back();
// Iterate over open parents while each sibling is closed.
while (node != nullptr && !node->closed) {
++num_newly_closed;
++num_closed_nodes_;
node->closed = true;
node->closing_clause_id = closing_clause_id;
// Keep the root trail_info so GetTrailInfo never returns nullptr.
if (node->parent != nullptr) {
ClearTrailInfo(node);
}
node->objective_lb = kMaxIntegerValue;
// If we are closing a leaf, try to maintain the same number of leaves;
num_splits_wanted_ += (node->children[0] == nullptr);
for (Node* child : node->children) {
if (child == nullptr || child->closed) continue;
ClauseId child_closing_clause_id = kNoClauseId;
if (lrat_proof_handler_ != nullptr) {
// The node's closing clause is sufficient to prove that `child` can
// be closed. We use a new clause only to avoid double deletes in
// RestartLockHeld().
child_closing_clause_id = clause_id_generator_.GetNextId();
lrat_proof_handler_->AddInferredClause(
child_closing_clause_id, ClosingClause(child),
{closing_clause_id}, /*exported=*/true);
}
to_close_.emplace_back(child, child_closing_clause_id);
}
Node* sibling = GetSibling(node);
if (sibling != nullptr) {
sibling->implied = true;
if (lrat_proof_handler_ != nullptr) {
newly_implied.push_back(sibling);
}
if (!sibling->closed) {
break;
}
}
Node* parent = node->parent;
if (lrat_proof_handler_ != nullptr && parent != nullptr &&
!parent->closed) {
closing_clause_id = clause_id_generator_.GetNextId();
// Combine the clauses proving that the node and its sibling could be
// closed to prove that the parent can be closed.
lrat_proof_handler_->AddInferredClause(
closing_clause_id, ClosingClause(parent),
{node->closing_clause_id, sibling->closing_clause_id},
/*exported=*/true);
}
node = parent;
}
DCHECK(node == nullptr || node->closed);
if (node == nullptr) {
shared_response_manager_->NotifyThatImprovingProblemIsInfeasible(
ShortStatus());
} else if (node->parent != nullptr) {
to_update_.push_back(node->parent);
}
}
if (num_newly_closed > 0) {
shared_response_manager_->LogMessageWithThrottling(
"Tree", absl::StrCat("closed:", num_closed_nodes_, "/", nodes_.size(),
" unassigned:", unassigned_leaves_.size(),
" restarts:", num_restarts_));
}
DCHECK(CheckLratInvariants());
// TODO(user): We could do resolution here by moving implications that
// are true in each child to the parent.
bool root_updated = false;
while (!to_update_.empty()) {
Node* node = to_update_.back();
to_update_.pop_back();
// Iterate over parents while the lower bound can be improved.
while (node != nullptr && !node->closed) {
DCHECK(node->children[0] != nullptr);
DCHECK(node->children[1] != nullptr);
for (Node* child : node->children) {
if (child->implied) {
if (child->trail_info != nullptr) {
DCHECK(!child->implied_and_processed);
ProcessImpliedNode(child);
ClearTrailInfo(child);
}
child->implied_and_processed = true;
}
}
IntegerValue child_bound = std::min(node->children[0]->objective_lb,
node->children[1]->objective_lb);
if (child_bound <= node->objective_lb) break;
node->objective_lb = child_bound;
node = node->parent;
}
if (node == nullptr) root_updated = true;
}
if (root_updated) {
shared_response_manager_->UpdateInnerObjectiveBounds(
ShortStatus(), nodes_[0].objective_lb, kMaxIntegerValue);
}
for (Node* node : newly_implied) {
if (!node->implied_and_processed) {
DCHECK_EQ(node->trail_info, nullptr);
DCHECK_NE(lrat_proof_handler_, nullptr);
ProcessImpliedNode(node);
node->implied_and_processed = true;
}
}
// These are shared via SharedBoundsManager, don't duplicate here.
ClearTrailInfo(&nodes_[0], /*implications_only=*/true);
DCHECK(CheckLratInvariants());
}
// Moves the trail_info implications of `node` to its first non-implied
// ancestor, and removes the newly implied literal from the closing and
// implication clauses of `node` and its descendants.
void SharedTreeManager::ProcessImpliedNode(Node* node) {
CHECK(node->parent != nullptr);
Node* first_non_implied_ancestor = node->parent;
while (first_non_implied_ancestor->trail_info == nullptr) {
first_non_implied_ancestor = first_non_implied_ancestor->parent;
DCHECK_NE(first_non_implied_ancestor, nullptr);
}
// Fast path for the common case where there is no need to add LRAT clauses.
// The rest of the code is only executed when LRAT is enabled, and assumes a
// pure SAT problem.
if (lrat_proof_handler_ == nullptr) {
first_non_implied_ancestor->trail_info->implications.merge(
node->trail_info->implications);
return;
}
// Gather the clauses needed to prove the new implications and closing
// clauses.
std::vector<ClauseId> clauses;
Node* n = node;
while (n->parent != nullptr) {
// Newly implied nodes must be removed from the closing and implication
// clauses, which requires a proof (already implied nodes are no longer in
// these clauses, so we don't need a proof for them).
if (n->implied && !n->implied_and_processed) {
clauses.push_back(GetSibling(n)->closing_clause_id);
}
n = n->parent;
}
std::reverse(clauses.begin(), clauses.end());
// Move the implications of `node` to the first non-implied ancestor.
if (node->trail_info != nullptr) {
for (const auto& [var, lb_and_clause] : node->trail_info->implications) {
// This is OK because we assume a pure SAT problem.
if (first_non_implied_ancestor->trail_info->implications.contains(var)) {
continue;
}
const auto [lb, clause_id] = lb_and_clause;
ClauseId new_clause_id = clause_id_generator_.GetNextId();
clauses.push_back(clause_id);
lrat_proof_handler_->AddInferredClause(
new_clause_id,
ImplicationClause(first_non_implied_ancestor, ProtoLiteral(var, lb),
/*skip_unprocessed_implied_nodes=*/true),
clauses, /*exported=*/true);
clauses.pop_back();
first_non_implied_ancestor->trail_info->implications.insert(
{var, std::make_pair(lb, new_clause_id)});
}
}
UpdateLratClausesInSubtree(node, node, clauses);
}
// Updates the closing clauses and the trail implication clauses of all the
// nodes in the subtree rooted at `node`, to maintain the LRAT invariants.
// Recursive method where `n` is a node of the subtree, and `clauses` are the
// clauses needed to infer its updated closing and implication clauses.
// TODO(user): change to a non-recursive implementation?
void SharedTreeManager::UpdateLratClausesInSubtree(
Node* node, Node* n, std::vector<ClauseId>& clauses) {
const bool implied_and_not_processed =
n->implied && !n->implied_and_processed;
if (implied_and_not_processed) {
// Newly implied nodes must be removed from the closing and implication
// clauses of `n`, which requires a proof (already implied nodes are no
// longer in these clauses, so we don't need a proof for them).
clauses.push_back(GetSibling(n)->closing_clause_id);
}
if (n->closed) {
DCHECK_NE(n->closing_clause_id, kNoClauseId);
ClauseId new_clause_id = clause_id_generator_.GetNextId();
clauses.push_back(n->closing_clause_id);
lrat_proof_handler_->AddInferredClause(
new_clause_id,
ClosingClause(n, /*skip_unprocessed_implied_nodes=*/true), clauses,
/*exported=*/true);
clauses.pop_back();
lrat_proof_handler_->DeleteClause(n->closing_clause_id, {});
n->closing_clause_id = new_clause_id;
}
if (n != node && n->trail_info != nullptr) {
for (auto& [var, lb_and_clause] : n->trail_info->implications) {
auto& [lb, clause_id] = lb_and_clause;
ClauseId new_clause_id = clause_id_generator_.GetNextId();
clauses.push_back(clause_id);
lrat_proof_handler_->AddInferredClause(
new_clause_id,
ImplicationClause(n, ProtoLiteral(var, lb),
/*skip_unprocessed_implied_nodes=*/true),
clauses, /*exported=*/true);
lrat_proof_handler_->DeleteClause(clause_id, {});
clause_id = new_clause_id;
clauses.pop_back();
}
}
// We can stop at implied but not yet processed nodes (they will be processed
// with further calls to ProcessImpliedNode()).
if (n == node || !(n->implied && n->trail_info != nullptr)) {
for (Node* child : n->children) {
if (child != nullptr && child->parent != nullptr) {
UpdateLratClausesInSubtree(node, child, clauses);
}
}
}
if (implied_and_not_processed) {
clauses.pop_back();
}
}
SharedTreeManager::Node* SharedTreeManager::GetNode(int id) {
const int index = id - node_id_offset_;
CHECK_GE(index, 0);
CHECK_LT(index, nodes_.size());
return &nodes_[index];
}
std::vector<std::pair<SharedTreeManager::Node*, int>>
SharedTreeManager::GetAssignedNodes(const ProtoTrail& path) {
std::vector<std::pair<Node*, int>> nodes({std::make_pair(&nodes_[0], 0)});
if (!IsValid(path)) {
// Restart has happened, nodes in this path are no longer valid, but the
// root is equivalent.
return nodes;
}
for (int i = 0; i <= path.MaxLevel(); ++i) {
for (int id : path.NodeIds(i)) {
const int index = id - node_id_offset_;
CHECK_GE(index, 0) << " in path.NodeIds(" << i
<< "), max_level=" << path.MaxLevel();
CHECK_LT(index, nodes_.size());
DCHECK_EQ(nodes.back().first, nodes_[index].parent);
nodes.push_back(std::make_pair(&nodes_[index], i));
}
}
return nodes;
}
void SharedTreeManager::CloseTree(ProtoTrail& path, int level) {
absl::MutexLock mutex_lock(mu_);
DCHECK(CheckLratInvariants());
const int node_id_to_close = path.NodeIds(level).front();
if (node_id_to_close < node_id_offset_) {
path.Clear();
return;
}
Node* node = &nodes_[node_id_to_close - node_id_offset_];
VLOG(2) << "Closing subtree at level " << level;
DCHECK(to_close_.empty());
ClauseId closing_clause_id = kNoClauseId;
if (lrat_proof_handler_ != nullptr) {
// For the worker providing `path`, `node` is implied by all the previous
// decisions in `path`, but for the manager we need a closing clause using
// `node` and its ancestors in the tree (with implied ones filtered out --
// they can be different because the manager and the worker have different
// views of the tree).
const std::vector<Literal> inferred_clause = ClosingClause(node);
std::vector<Literal> imported_clause;
std::vector<ClauseId> lrat_proof;
for (int l = 1; l <= level; ++l) {
Node* n = GetNode(path.DecisionNodeId(l));
const Literal decision = DecodeWithIdentityMapping(n->decision);
imported_clause.push_back(decision.Negated());
if (n->implied_and_processed) {
lrat_proof.push_back(GetSibling(n)->closing_clause_id);
}
}
closing_clause_id = AddImportedAndInferredClauses(
imported_clause, inferred_clause, lrat_proof);
}
path.Clear();
to_close_.emplace_back(node, closing_clause_id);
ProcessNodeChanges();
DCHECK(CheckLratInvariants());
}
bool SharedTreeManager::IsDecisionOfNodeOrAncestor(ProtoLiteral literal,
const Node* node) const {
CHECK_NE(node, nullptr);
while (node->parent != nullptr) {
if (literal == node->decision) return true;
node = node->parent;
}
return false;
}
std::vector<Literal> SharedTreeManager::ImplicationClause(
const Node* node, ProtoLiteral implied,
bool skip_unprocessed_implied_nodes) const {
// This is only used for LRAT, which only works for pure SAT, without
// presolve. In this case all workers should have the same identity mapping
// from the proto variables.
CHECK_NE(node, nullptr);
std::vector<Literal> clause =
ClosingClause(node, skip_unprocessed_implied_nodes);
clause.push_back(DecodeWithIdentityMapping(implied));
return clause;
}
std::vector<Literal> SharedTreeManager::ClosingClause(
const Node* node, bool skip_unprocessed_implied_nodes) const {
// This is only used for LRAT, which only works for pure SAT, without
// presolve. In this case all workers should have the same identity mapping
// from the proto variables.
CHECK_NE(node, nullptr);
std::vector<Literal> clause;
while (node->parent != nullptr) {
// When a node is implied its implications are moved to its first
// non-implied ancestor, instead of to its parent. Proving this with the
// clause that the node is implied requires the implication clauses to
// exclude the decisions of implied nodes. And since the clause that a node
// is implied is the closing clause of its sibling, closing clauses should
// also exclude the decisions of implied nodes.
const bool is_implied = node->implied && (node->implied_and_processed ||
skip_unprocessed_implied_nodes);
if (!is_implied) {
clause.push_back(DecodeWithIdentityMapping(node->decision).Negated());
}
node = node->parent;
}
return clause;
}
namespace {
bool UnorderedSpansAreEqual(absl::Span<const Literal> a,
absl::Span<const Literal> b) {
if (a.size() != b.size()) return false;
std::vector<Literal> sorted_a(a.begin(), a.end());
std::vector<Literal> sorted_b(b.begin(), b.end());
std::sort(sorted_a.begin(), sorted_a.end());
std::sort(sorted_b.begin(), sorted_b.end());
return sorted_a == sorted_b;
}
} // namespace
ClauseId SharedTreeManager::AddImportedAndInferredClauses(
absl::Span<const Literal> imported_clause,
absl::Span<const Literal> inferred_clause,
std::vector<ClauseId>& lrat_proof) {
const ClauseId id = clause_id_generator_.GetNextId();
lrat_proof_handler_->AddImportedClause(id, imported_clause);
if (!lrat_proof.empty() ||
!UnorderedSpansAreEqual(inferred_clause, imported_clause)) {
lrat_proof.push_back(id);
const ClauseId new_id = clause_id_generator_.GetNextId();
lrat_proof_handler_->AddInferredClause(new_id, inferred_clause, lrat_proof,
/*exported=*/true);
lrat_proof_handler_->DeleteClause(id, {});
return new_id;
} else {
return id;
}
}
void SharedTreeManager::AssignLeaf(ProtoTrail& path, Node* leaf) {
path.Clear();
std::vector<Node*> reversed_path;
while (leaf != &nodes_[0]) {
reversed_path.push_back(&nodes_[leaf->id - node_id_offset_]);
leaf = leaf->parent;
}
while (!reversed_path.empty()) {
Node* leaf = reversed_path.back();
reversed_path.pop_back();
path.PushLevel(leaf->decision, leaf->objective_lb, leaf->id);
if (leaf->implied) {
path.SetLevelImplied(path.MaxLevel());
}
if (params_.shared_tree_worker_enable_trail_sharing() &&
leaf->trail_info != nullptr) {
for (const auto& [var, lb_and_clause] : leaf->trail_info->implications) {
const auto [lb, clause_id] = lb_and_clause;
path.AddImplication(path.MaxLevel(), ProtoLiteral(var, lb));
}
}
}
}
bool SharedTreeManager::IsValid(const ProtoTrail& path) const {
auto node_ids = path.NodeIds(path.MaxLevel());
if (node_ids.empty()) return true;
if (node_ids.back() < node_id_offset_) return false;
return true;
}
void SharedTreeManager::RestartLockHeld() {
node_id_offset_ += nodes_.size();
if (lrat_proof_handler_ != nullptr) {
for (const Node& node : nodes_) {
if (node.closing_clause_id != kNoClauseId) {
lrat_proof_handler_->DeleteClause(node.closing_clause_id, {});
}
}
}
nodes_.resize(1);
nodes_[0].id = node_id_offset_;
nodes_[0].children = {nullptr, nullptr};
unassigned_leaves_.clear();
DCHECK(to_close_.empty());
DCHECK(to_update_.empty());
num_splits_wanted_ =
num_workers_ * params_.shared_tree_open_leaves_per_worker() - 1;
num_closed_nodes_ = 0;
num_restarts_ += 1;
num_leaves_assigned_since_restart_ = 0;
}
void SharedTreeManager::CloseLratProof() {
absl::MutexLock l(mu_);
if (lrat_proof_handler_ != nullptr) {
lrat_proof_handler_->Close(/*model_is_unsat=*/false);
lrat_proof_handler_.reset();
}
}
std::string SharedTreeManager::ShortStatus() const {
return absl::StrCat("shared_tree_manager(r=", num_restarts_,
" n=", nodes_.size(), ")");
}
namespace {
void CheckEqual(absl::Span<const Literal> a, absl::Span<const Literal> b) {
std::vector<Literal> sorted_a(a.begin(), a.end());