forked from rte-france/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primal_dual_hybrid_gradient.cc
2129 lines (1990 loc) · 95.9 KB
/
primal_dual_hybrid_gradient.cc
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-2022 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/pdlp/primal_dual_hybrid_gradient.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <functional>
#include <limits>
#include <optional>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "Eigen/Core"
#include "Eigen/SparseCore"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "ortools/base/check.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/timer.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/glop/preprocessor.h"
#include "ortools/linear_solver/linear_solver.pb.h"
#include "ortools/lp_data/lp_data.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/lp_data/proto_utils.h"
#include "ortools/pdlp/iteration_stats.h"
#include "ortools/pdlp/quadratic_program.h"
#include "ortools/pdlp/sharded_optimization_utils.h"
#include "ortools/pdlp/sharded_quadratic_program.h"
#include "ortools/pdlp/sharder.h"
#include "ortools/pdlp/solve_log.pb.h"
#include "ortools/pdlp/solvers.pb.h"
#include "ortools/pdlp/solvers_proto_validation.h"
#include "ortools/pdlp/termination.h"
#include "ortools/pdlp/trust_region.h"
namespace operations_research::pdlp {
namespace {
using ::Eigen::VectorXd;
using IterationStatsCallback =
std::function<void(const IterationCallbackInfo&)>;
// Computes a `num_threads' that is capped by the problem size and num_shards,
// if specified, to avoid creating unusable threads.
int NumThreads(const int num_threads, const int num_shards,
const QuadraticProgram& qp) {
int capped_num_threads = num_threads;
if (num_shards > 0) {
capped_num_threads = std::min(capped_num_threads, num_shards);
}
const int64_t problem_limit = std::max(qp.variable_lower_bounds.size(),
qp.constraint_lower_bounds.size());
capped_num_threads =
static_cast<int>(std::min(int64_t{capped_num_threads}, problem_limit));
capped_num_threads = std::max(capped_num_threads, 1);
if (capped_num_threads != num_threads) {
LOG(WARNING) << "Reducing num_threads from " << num_threads << " to "
<< capped_num_threads
<< " because additional threads would be useless.";
}
return capped_num_threads;
}
// If `num_shards' is positive, returns it. Otherwise returns a reasonable
// number of shards to use with ShardedQuadraticProgram for the given number of
// threads.
int NumShards(const int num_threads, const int num_shards) {
if (num_shards > 0) return num_shards;
return num_threads == 1 ? 1 : 4 * num_threads;
}
std::string ToString(const ConvergenceInformation& convergence_information,
const RelativeConvergenceInformation& relative_information,
const OptimalityNorm residual_norm) {
constexpr absl::string_view kFormatStr =
"%#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g | "
"%#12.6g %#12.6g";
switch (residual_norm) {
case OPTIMALITY_NORM_L2:
return absl::StrFormat(kFormatStr,
relative_information.relative_l2_primal_residual,
relative_information.relative_l2_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.l2_primal_residual(),
convergence_information.l2_dual_residual(),
convergence_information.primal_objective() -
convergence_information.dual_objective(),
convergence_information.primal_objective(),
convergence_information.dual_objective(),
convergence_information.l2_primal_variable(),
convergence_information.l2_dual_variable());
case OPTIMALITY_NORM_L_INF:
return absl::StrFormat(
kFormatStr, relative_information.relative_l_inf_primal_residual,
relative_information.relative_l_inf_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.l_inf_primal_residual(),
convergence_information.l_inf_dual_residual(),
convergence_information.primal_objective() -
convergence_information.dual_objective(),
convergence_information.primal_objective(),
convergence_information.dual_objective(),
convergence_information.l2_primal_variable(),
convergence_information.l2_dual_variable());
case OPTIMALITY_NORM_UNSPECIFIED:
LOG(FATAL) << "Invalid residual norm.";
}
}
std::string ToShortString(
const ConvergenceInformation& convergence_information,
const RelativeConvergenceInformation& relative_information,
const OptimalityNorm residual_norm) {
constexpr absl::string_view kFormatStr =
"%#10.4g %#10.4g %#10.4g | %#10.4g %#10.4g";
switch (residual_norm) {
case OPTIMALITY_NORM_L2:
return absl::StrFormat(kFormatStr,
relative_information.relative_l2_primal_residual,
relative_information.relative_l2_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.primal_objective(),
convergence_information.dual_objective());
case OPTIMALITY_NORM_L_INF:
return absl::StrFormat(
kFormatStr, relative_information.relative_l_inf_primal_residual,
relative_information.relative_l_inf_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.primal_objective(),
convergence_information.dual_objective());
case OPTIMALITY_NORM_UNSPECIFIED:
LOG(FATAL) << "Invalid residual norm.";
}
}
// Returns a string describing iter_stats, based on the ConvergenceInformation
// with candidate_type==preferred_candidate if one exists, otherwise based on
// the first value, if any. termination_criteria.optimality_norm determines the
// norm in which the residuals are displayed.
std::string ToString(const IterationStats& iter_stats,
const TerminationCriteria& termination_criteria,
const QuadraticProgramBoundNorms& bound_norms,
PointType preferred_candidate) {
std::string iteration_string =
absl::StrFormat("%6d %8.1f %6.1f", iter_stats.iteration_number(),
iter_stats.cumulative_kkt_matrix_passes(),
iter_stats.cumulative_time_sec());
auto convergence_information =
GetConvergenceInformation(iter_stats, preferred_candidate);
if (!convergence_information.has_value() &&
iter_stats.convergence_information_size() > 0) {
convergence_information = iter_stats.convergence_information(0);
}
if (convergence_information.has_value()) {
const RelativeConvergenceInformation relative_information =
ComputeRelativeResiduals(
EffectiveOptimalityCriteria(termination_criteria),
*convergence_information, bound_norms);
return absl::StrCat(iteration_string, " | ",
ToString(*convergence_information, relative_information,
termination_criteria.optimality_norm()));
}
return iteration_string;
}
std::string ToShortString(const IterationStats& iter_stats,
const TerminationCriteria& termination_criteria,
const QuadraticProgramBoundNorms& bound_norms,
PointType preferred_candidate) {
std::string iteration_string =
absl::StrFormat("%6d %6.1f", iter_stats.iteration_number(),
iter_stats.cumulative_time_sec());
auto convergence_information =
GetConvergenceInformation(iter_stats, preferred_candidate);
if (!convergence_information.has_value() &&
iter_stats.convergence_information_size() > 0) {
convergence_information = iter_stats.convergence_information(0);
}
if (convergence_information.has_value()) {
const RelativeConvergenceInformation relative_information =
ComputeRelativeResiduals(
EffectiveOptimalityCriteria(termination_criteria),
*convergence_information, bound_norms);
return absl::StrCat(
iteration_string, " | ",
ToShortString(*convergence_information, relative_information,
termination_criteria.optimality_norm()));
}
return iteration_string;
}
// Returns a label string corresponding to the format of ToString().
std::string ConvergenceInformationLabelString() {
return absl::StrFormat(
"%12s %12s %12s | %12s %12s %12s | %12s %12s | %12s %12s", "rel_prim_res",
"rel_dual_res", "rel_gap", "prim_resid", "dual_resid", "obj_gap",
"prim_obj", "dual_obj", "prim_var_l2", "dual_var_l2");
}
std::string ConvergenceInformationLabelShortString() {
return absl::StrFormat("%10s %10s %10s | %10s %10s", "rel_p_res", "rel_d_res",
"rel_gap", "prim_obj", "dual_obj");
}
std::string IterationStatsLabelString() {
return absl::StrCat(
absl::StrFormat("%6s %8s %6s", "iter#", "kkt_pass", "time"), " | ",
ConvergenceInformationLabelString());
}
std::string IterationStatsLabelShortString() {
return absl::StrCat(absl::StrFormat("%6s %6s", "iter#", "time"), " | ",
ConvergenceInformationLabelShortString());
}
enum class InnerStepOutcome {
kSuccessful,
kForceNumericalTermination,
};
class Solver {
public:
// Assumes that the qp and params are valid.
// Note that the qp is intentionally passed by value.
Solver(QuadraticProgram qp, const PrimalDualHybridGradientParams& params);
// Not copyable or movable because of const and reference members.
Solver(const Solver&) = delete;
Solver& operator=(const Solver&) = delete;
// Zero is used if initial_solution is nullopt.
SolverResult Solve(std::optional<PrimalAndDualSolution> initial_solution,
const std::atomic<bool>* interrupt_solve,
IterationStatsCallback iteration_stats_callback);
private:
struct NextSolutionAndDelta {
VectorXd value;
// delta is value - current_solution.
VectorXd delta;
};
struct DistanceBasedRestartInfo {
double distance_moved_last_restart_period;
int length_of_last_restart_period;
};
struct PresolveInfo {
explicit PresolveInfo(ShardedQuadraticProgram original_qp,
const PrimalDualHybridGradientParams& params)
: preprocessor_parameters(PreprocessorParameters(params)),
preprocessor(&preprocessor_parameters),
sharded_original_qp(std::move(original_qp)),
trivial_col_scaling_vec(
OnesVector(sharded_original_qp.PrimalSharder())),
trivial_row_scaling_vec(
OnesVector(sharded_original_qp.DualSharder())) {}
glop::GlopParameters preprocessor_parameters;
glop::MainLpPreprocessor preprocessor;
ShardedQuadraticProgram sharded_original_qp;
bool presolved_problem_was_maximization = false;
const VectorXd trivial_col_scaling_vec, trivial_row_scaling_vec;
};
// Movement terms (weighted squared norms of primal and dual deltas) larger
// than this cause termination because iterates are diverging, and likely to
// cause infinite and NaN values.
constexpr static double kDivergentMovement = 1.0e100;
NextSolutionAndDelta ComputeNextPrimalSolution(double primal_step_size) const;
NextSolutionAndDelta ComputeNextDualSolution(
double dual_step_size, double extrapolation_factor,
const NextSolutionAndDelta& next_primal) const;
double ComputeMovement(const VectorXd& delta_primal,
const VectorXd& delta_dual) const;
double ComputeNonlinearity(const VectorXd& delta_primal,
const VectorXd& next_dual_product) const;
// Creates all the simple-to-compute statistics in stats.
IterationStats CreateSimpleIterationStats(RestartChoice restart_used) const;
RestartChoice ChooseRestartToApply(bool is_major_iteration);
VectorXd PrimalAverage() const;
VectorXd DualAverage() const;
double ComputeNewPrimalWeight() const;
// Picks the primal and dual solutions according to output_type, unscales them
// and makes the closing changes to the SolveLog. This function should only be
// called once the solver is finishing its execution.
// NOTE: The primal_solution and dual_solution are used as the output except
// when output_type is POINT_TYPE_CURRENT_ITERATE or
// POINT_TYPE_ITERATE_DIFFERENCE, in which case the values are computed from
// Solver data. NOTE: Both primal_solution and dual_solution are passed by
// copy. To avoid unnecessary copying, move these objects (i.e. use
// std::move()).
SolverResult ConstructSolverResult(VectorXd primal_solution,
VectorXd dual_solution,
const IterationStats& stats,
TerminationReason termination_reason,
PointType output_type,
SolveLog solve_log) const;
// Adds one entry of convergence information and infeasibility information to
// stats using the input solutions. The primal_solution and dual_solution are
// solutions for sharded_qp. The col_scaling_vec and row_scaling_vec are used
// to implicitly unscale sharded_qp when computing the relevant information.
void AddConvergenceAndInfeasibilityInformation(
const VectorXd& primal_solution, const VectorXd& dual_solution,
const ShardedQuadraticProgram& sharded_qp,
const VectorXd& col_scaling_vec, const VectorXd& row_scaling_vec,
PointType candidate_type, IterationStats& stats) const;
// Adds one entry of PointMetadata to stats using the input solutions.
void AddPointMetadata(const VectorXd& primal_solution,
const VectorXd& dual_solution, PointType point_type,
IterationStats& stats) const;
// Returns a TerminationReasonAndPointType when the termination criteria are
// satisfied, otherwise returns nothing. Uses the primal and dual vectors to
// compute solution statistics and adds them to the stats proto.
// NOTE: The primal and dual input pair should be a scaled solution.
std::optional<TerminationReasonAndPointType>
UpdateIterationStatsAndCheckTermination(
bool force_numerical_termination, const VectorXd& primal_average,
const VectorXd& dual_average, const std::atomic<bool>* interrupt_solve,
IterationStats& stats) const;
double DistanceTraveledFromLastStart(const VectorXd& primal_solution,
const VectorXd& dual_solution) const;
LocalizedLagrangianBounds ComputeLocalizedBoundsAtCurrent() const;
LocalizedLagrangianBounds ComputeLocalizedBoundsAtAverage() const;
double InitialPrimalWeight(double l2_norm_primal_linear_objective,
double l2_norm_constraint_bounds) const;
void ComputeAndApplyRescaling();
// Applies the given RestartChoice. If a restart is chosen, updates the
// state of the algorithm accordingly and computes a new primal weight.
void ApplyRestartChoice(RestartChoice restart_to_apply);
std::optional<SolverResult> MajorIterationAndTerminationCheck(
bool force_numerical_termination,
const std::atomic<bool>* interrupt_solve, SolveLog& solve_log);
bool ShouldDoAdaptiveRestartHeuristic(double candidate_normalized_gap) const;
RestartChoice DetermineDistanceBasedRestartChoice() const;
void ResetAverageToCurrent();
void LogNumericalTermination() const;
void LogInnerIterationLimitHit() const;
void LogQuadraticProgramStats(const QuadraticProgramStats& stats);
// Takes a step based on the Malitsky and Pock linesearch algorithm.
// (https://arxiv.org/pdf/1608.08883.pdf)
// The current implementation is provably convergent (at an optimal rate)
// for LP programs (provided we do not change the primal weight at every major
// iteration). Further, we have observed that this rule is very sensitive to
// the parameter choice whenever we apply the primal weight recomputation
// heuristic.
InnerStepOutcome TakeMalitskyPockStep();
// Takes a step based on the adaptive heuristic presented in Section 3.1 of
// https://arxiv.org/pdf/2106.04756.pdf (further generalized to QP).
InnerStepOutcome TakeAdaptiveStep();
// Takes a constant-size step.
InnerStepOutcome TakeConstantSizeStep();
const QuadraticProgram& WorkingQp() const { return sharded_working_qp_.Qp(); }
// TODO(user): experiment with different preprocessor types.
static glop::GlopParameters PreprocessorParameters(
const PrimalDualHybridGradientParams& params);
// If presolve is enabled, moves sharded_working_qp_ to
// presolve_info_.sharded_original_qp and computes the presolved linear
// program and installs it in sharded_working_qp_. Clears initial_solution if
// presolve is enabled. If presolve solves the problem completely returns the
// appropriate TerminationReason. Otherwise returns nullopt. If presolve
// is disabled or an error occurs modifies nothing and returns nullopt.
std::optional<TerminationReason> ApplyPresolveIfEnabled(
std::optional<PrimalAndDualSolution>* initial_solution);
PrimalAndDualSolution RecoverOriginalSolution(
PrimalAndDualSolution working_solution) const;
WallTimer timer_;
const PrimalDualHybridGradientParams params_;
const int num_threads_;
const int num_shards_;
// This is the QP that PDHG is run on. It has been reduced by presolve and/or
// rescaled, if those are enabled. The original problem is available in
// presolve_info_->sharded_original_qp if presolve_info_.has_value(), and
// otherwise can be obtained by undoing the scaling of sharded_working_qp_ by
// col_scaling_vec_ and row_scaling_vec_.
ShardedQuadraticProgram sharded_working_qp_;
ShardedWeightedAverage primal_average_;
ShardedWeightedAverage dual_average_;
IterationStatsCallback iteration_stats_callback_;
QuadraticProgramBoundNorms original_bound_norms_;
// Set iff presolve is enabled.
std::optional<PresolveInfo> presolve_info_;
double step_size_;
// For Malitsky-Pock linesearch only: step_size_ / previous_step_size
double ratio_last_two_step_sizes_;
double primal_weight_;
// For adaptive restarts only.
double normalized_gap_at_last_trial_ =
std::numeric_limits<double>::infinity();
// For adaptive restarts only.
double normalized_gap_at_last_restart_ =
std::numeric_limits<double>::infinity();
int iterations_completed_;
int num_rejected_steps_;
VectorXd current_primal_solution_;
VectorXd current_dual_solution_;
VectorXd current_primal_delta_;
VectorXd current_dual_delta_;
// A cache of constraint_matrix.transpose() * current_dual_solution.
VectorXd current_dual_product_;
// The primal point at which the algorithm was last restarted from, or
// the initial primal starting point if no restart has occurred.
VectorXd last_primal_start_point_;
// The dual point at which the algorithm was last restarted from, or
// the initial dual starting point if no restart has occurred.
VectorXd last_dual_start_point_;
// Information for deciding whether to trigger a distance-based restart.
// The distances are initialized to +inf to force a restart during the first
// major iteration check.
DistanceBasedRestartInfo distance_based_restart_info_ = {
.distance_moved_last_restart_period =
std::numeric_limits<double>::infinity(),
.length_of_last_restart_period = 1,
};
// The scaling vectors that map the original (or presolved) quadratic program
// to the working version. See
// ShardedQuadraticProgram::RescaleQuadraticProgram() for details.
VectorXd col_scaling_vec_;
VectorXd row_scaling_vec_;
};
Solver::Solver(QuadraticProgram qp,
const PrimalDualHybridGradientParams& params)
: params_(params),
num_threads_(NumThreads(params.num_threads(), params.num_shards(), qp)),
num_shards_(NumShards(num_threads_, params.num_shards())),
sharded_working_qp_(std::move(qp), num_threads_, num_shards_),
primal_average_(&sharded_working_qp_.PrimalSharder()),
dual_average_(&sharded_working_qp_.DualSharder()) {}
Solver::NextSolutionAndDelta Solver::ComputeNextPrimalSolution(
double primal_step_size) const {
const int64_t primal_size = sharded_working_qp_.PrimalSize();
NextSolutionAndDelta result = {
.value = VectorXd(primal_size),
.delta = VectorXd(primal_size),
};
const QuadraticProgram& qp = WorkingQp();
// This computes the primal portion of the PDHG algorithm:
// argmin_x[gradient(f)(current_primal_solution)'x + g(x)
// + current_dual_solution' K x
// + (0.5 / primal_step_size) * norm(x - current_primal_solution) ^ 2]
// See Sections 2 - 3 of Chambolle and Pock and the comment in the header.
// We omitted the constant terms from Chambolle and Pock's (7).
// This minimization is easy to do in closed form since it can be separated
// into independent problems for each of the primal variables.
sharded_working_qp_.PrimalSharder().ParallelForEachShard(
[&](const Sharder::Shard& shard) {
if (!IsLinearProgram(qp)) {
const VectorXd diagonal_scaling =
primal_step_size *
shard(qp.objective_matrix->diagonal()).array() +
1.0;
shard(result.value) =
(shard(current_primal_solution_) -
primal_step_size *
(shard(qp.objective_vector) - shard(current_dual_product_)))
// Scale i-th element by 1 / (1 + primal_step_size * Q_{ii})
.cwiseQuotient(diagonal_scaling)
.cwiseMin(shard(qp.variable_upper_bounds))
.cwiseMax(shard(qp.variable_lower_bounds));
} else {
// The formula in the LP case is simplified for better performance.
shard(result.value) =
(shard(current_primal_solution_) -
primal_step_size *
(shard(qp.objective_vector) - shard(current_dual_product_)))
.cwiseMin(shard(qp.variable_upper_bounds))
.cwiseMax(shard(qp.variable_lower_bounds));
}
shard(result.delta) =
shard(result.value) - shard(current_primal_solution_);
});
return result;
}
Solver::NextSolutionAndDelta Solver::ComputeNextDualSolution(
double dual_step_size, double extrapolation_factor,
const NextSolutionAndDelta& next_primal_solution) const {
const int64_t dual_size = sharded_working_qp_.DualSize();
NextSolutionAndDelta result = {
.value = VectorXd(dual_size),
.delta = VectorXd(dual_size),
};
const QuadraticProgram& qp = WorkingQp();
VectorXd extrapolated_primal(sharded_working_qp_.PrimalSize());
sharded_working_qp_.PrimalSharder().ParallelForEachShard(
[&](const Sharder::Shard& shard) {
shard(extrapolated_primal) =
(shard(next_primal_solution.value) +
extrapolation_factor * shard(next_primal_solution.delta));
});
// TODO(user): Refactor this multiplication so that we only do one matrix
// vector mutiply for the primal variable. This only applies to Malitsky and
// Pock and not to the adaptive step size rule.
sharded_working_qp_.TransposedConstraintMatrixSharder().ParallelForEachShard(
[&](const Sharder::Shard& shard) {
VectorXd temp =
shard(current_dual_solution_) -
dual_step_size *
shard(sharded_working_qp_.TransposedConstraintMatrix())
.transpose() *
extrapolated_primal;
// Each element of the argument of the cwiseMin is the critical point
// of the respective 1D minimization problem if it's negative.
// Likewise the argument to the cwiseMax is the critical point if
// positive.
shard(result.value) =
VectorXd::Zero(temp.size())
.cwiseMin(temp +
dual_step_size * shard(qp.constraint_upper_bounds))
.cwiseMax(temp +
dual_step_size * shard(qp.constraint_lower_bounds));
shard(result.delta) =
(shard(result.value) - shard(current_dual_solution_));
});
return result;
}
double Solver::ComputeMovement(const VectorXd& delta_primal,
const VectorXd& delta_dual) const {
const double primal_movement =
(0.5 * primal_weight_) *
SquaredNorm(delta_primal, sharded_working_qp_.PrimalSharder());
const double dual_movement =
(0.5 / primal_weight_) *
SquaredNorm(delta_dual, sharded_working_qp_.DualSharder());
return primal_movement + dual_movement;
}
double Solver::ComputeNonlinearity(const VectorXd& delta_primal,
const VectorXd& next_dual_product) const {
// Lemma 1 in Chambolle and Pock includes a term with L_f, the Lipshitz
// constant of f. This is zero in our formulation.
return sharded_working_qp_.PrimalSharder().ParallelSumOverShards(
[&](const Sharder::Shard& shard) {
return -shard(delta_primal)
.dot(shard(next_dual_product) -
shard(current_dual_product_));
});
}
IterationStats Solver::CreateSimpleIterationStats(
RestartChoice restart_used) const {
IterationStats stats;
double num_kkt_passes_per_rejected_step = 1.0;
if (params_.linesearch_rule() ==
PrimalDualHybridGradientParams::MALITSKY_POCK_LINESEARCH_RULE) {
num_kkt_passes_per_rejected_step = 0.5;
}
stats.set_iteration_number(iterations_completed_);
stats.set_cumulative_rejected_steps(num_rejected_steps_);
// TODO(user): This formula doesn't account for kkt passes in major
// iterations.
stats.set_cumulative_kkt_matrix_passes(iterations_completed_ +
num_kkt_passes_per_rejected_step *
num_rejected_steps_);
stats.set_cumulative_time_sec(timer_.Get());
stats.set_restart_used(restart_used);
stats.set_step_size(step_size_);
stats.set_primal_weight(primal_weight_);
return stats;
}
double Solver::DistanceTraveledFromLastStart(
const VectorXd& primal_solution, const VectorXd& dual_solution) const {
return std::sqrt((0.5 * primal_weight_) *
SquaredDistance(primal_solution,
last_primal_start_point_,
sharded_working_qp_.PrimalSharder()) +
(0.5 / primal_weight_) *
SquaredDistance(dual_solution, last_dual_start_point_,
sharded_working_qp_.DualSharder()));
}
LocalizedLagrangianBounds Solver::ComputeLocalizedBoundsAtCurrent() const {
const double distance_traveled_by_current = DistanceTraveledFromLastStart(
current_primal_solution_, current_dual_solution_);
return ComputeLocalizedLagrangianBounds(
sharded_working_qp_, current_primal_solution_, current_dual_solution_,
PrimalDualNorm::kEuclideanNorm, primal_weight_,
distance_traveled_by_current,
/*primal_product=*/nullptr, ¤t_dual_product_,
params_.use_diagonal_qp_trust_region_solver(),
params_.diagonal_qp_trust_region_solver_tolerance());
}
LocalizedLagrangianBounds Solver::ComputeLocalizedBoundsAtAverage() const {
// TODO(user): These vectors are recomputed again for termination checks
// and again if we eventually restart to the average.
VectorXd average_primal = PrimalAverage();
VectorXd average_dual = DualAverage();
const double distance_traveled_by_average =
DistanceTraveledFromLastStart(average_primal, average_dual);
return ComputeLocalizedLagrangianBounds(
sharded_working_qp_, average_primal, average_dual,
PrimalDualNorm::kEuclideanNorm, primal_weight_,
distance_traveled_by_average,
/*primal_product=*/nullptr, /*dual_product=*/nullptr,
params_.use_diagonal_qp_trust_region_solver(),
params_.diagonal_qp_trust_region_solver_tolerance());
}
bool AverageHasBetterPotential(
const LocalizedLagrangianBounds& local_bounds_at_average,
const LocalizedLagrangianBounds& local_bounds_at_current) {
return BoundGap(local_bounds_at_average) /
MathUtil::Square(local_bounds_at_average.radius) <
BoundGap(local_bounds_at_current) /
MathUtil::Square(local_bounds_at_current.radius);
}
double NormalizedGap(
const LocalizedLagrangianBounds& local_bounds_at_candidate) {
const double distance_traveled_by_candidate =
local_bounds_at_candidate.radius;
return BoundGap(local_bounds_at_candidate) / distance_traveled_by_candidate;
}
// TODO(user): Review / cleanup adaptive heuristic.
bool Solver::ShouldDoAdaptiveRestartHeuristic(
double candidate_normalized_gap) const {
const double gap_reduction_ratio =
candidate_normalized_gap / normalized_gap_at_last_restart_;
if (gap_reduction_ratio < params_.sufficient_reduction_for_restart()) {
return true;
}
if (gap_reduction_ratio < params_.necessary_reduction_for_restart() &&
candidate_normalized_gap > normalized_gap_at_last_trial_) {
// We've made the "necessary" amount of progress, and iterates appear to
// be getting worse, so restart.
return true;
}
return false;
}
RestartChoice Solver::DetermineDistanceBasedRestartChoice() const {
// The following checks are safeguards that normally should not be triggered.
if (primal_average_.NumTerms() == 0) {
return RESTART_CHOICE_NO_RESTART;
} else if (distance_based_restart_info_.length_of_last_restart_period == 0) {
return RESTART_CHOICE_RESTART_TO_AVERAGE;
}
const int restart_period_length = primal_average_.NumTerms();
const double distance_moved_this_restart_period_by_average =
DistanceTraveledFromLastStart(primal_average_.ComputeAverage(),
dual_average_.ComputeAverage());
const double distance_moved_last_restart_period =
distance_based_restart_info_.distance_moved_last_restart_period;
// A restart should be triggered when the normalized distance traveled by
// the average is at least a constant factor smaller than the last.
// TODO(user): Experiment with using .necessary_reduction_for_restart()
// as a heuristic when deciding if a restart should be triggered.
if ((distance_moved_this_restart_period_by_average / restart_period_length) <
params_.sufficient_reduction_for_restart() *
(distance_moved_last_restart_period /
distance_based_restart_info_.length_of_last_restart_period)) {
// Restart at current solution when it yields a smaller normalized potential
// function value than the average (heuristic suggested by ohinder@).
if (AverageHasBetterPotential(ComputeLocalizedBoundsAtAverage(),
ComputeLocalizedBoundsAtCurrent())) {
return RESTART_CHOICE_RESTART_TO_AVERAGE;
} else {
return RESTART_CHOICE_WEIGHTED_AVERAGE_RESET;
}
} else {
return RESTART_CHOICE_NO_RESTART;
}
}
RestartChoice Solver::ChooseRestartToApply(const bool is_major_iteration) {
if (!primal_average_.HasNonzeroWeight() &&
!dual_average_.HasNonzeroWeight()) {
return RESTART_CHOICE_NO_RESTART;
}
// TODO(user): This forced restart is very important for the performance of
// ADAPTIVE_HEURISTIC. Test if the impact comes primarily from the first
// forced restart (which would unseat a good initial starting point that could
// prevent restarts early in the solve) or if it's really needed for the full
// duration of the solve. If it is really needed, should we then trigger major
// iterations on powers of two?
const int restart_length = primal_average_.NumTerms();
if (restart_length >= iterations_completed_ / 2 &&
params_.restart_strategy() ==
PrimalDualHybridGradientParams::ADAPTIVE_HEURISTIC) {
if (AverageHasBetterPotential(ComputeLocalizedBoundsAtAverage(),
ComputeLocalizedBoundsAtCurrent())) {
return RESTART_CHOICE_RESTART_TO_AVERAGE;
} else {
return RESTART_CHOICE_WEIGHTED_AVERAGE_RESET;
}
}
if (is_major_iteration) {
switch (params_.restart_strategy()) {
case PrimalDualHybridGradientParams::NO_RESTARTS:
return RESTART_CHOICE_WEIGHTED_AVERAGE_RESET;
case PrimalDualHybridGradientParams::EVERY_MAJOR_ITERATION:
return RESTART_CHOICE_RESTART_TO_AVERAGE;
case PrimalDualHybridGradientParams::ADAPTIVE_HEURISTIC: {
const LocalizedLagrangianBounds local_bounds_at_average =
ComputeLocalizedBoundsAtAverage();
const LocalizedLagrangianBounds local_bounds_at_current =
ComputeLocalizedBoundsAtCurrent();
double normalized_gap;
RestartChoice choice;
if (AverageHasBetterPotential(local_bounds_at_average,
local_bounds_at_current)) {
normalized_gap = NormalizedGap(local_bounds_at_average);
choice = RESTART_CHOICE_RESTART_TO_AVERAGE;
} else {
normalized_gap = NormalizedGap(local_bounds_at_current);
choice = RESTART_CHOICE_WEIGHTED_AVERAGE_RESET;
}
if (ShouldDoAdaptiveRestartHeuristic(normalized_gap)) {
return choice;
} else {
normalized_gap_at_last_trial_ = normalized_gap;
return RESTART_CHOICE_NO_RESTART;
}
}
case PrimalDualHybridGradientParams::ADAPTIVE_DISTANCE_BASED: {
return DetermineDistanceBasedRestartChoice();
}
default:
LOG(FATAL) << "Unrecognized restart_strategy "
<< params_.restart_strategy();
return RESTART_CHOICE_UNSPECIFIED;
}
} else {
return RESTART_CHOICE_NO_RESTART;
}
}
VectorXd Solver::PrimalAverage() const {
if (primal_average_.HasNonzeroWeight()) {
return primal_average_.ComputeAverage();
} else {
return current_primal_solution_;
}
}
VectorXd Solver::DualAverage() const {
if (dual_average_.HasNonzeroWeight()) {
return dual_average_.ComputeAverage();
} else {
return current_dual_solution_;
}
}
double Solver::ComputeNewPrimalWeight() const {
const double primal_distance =
Distance(current_primal_solution_, last_primal_start_point_,
sharded_working_qp_.PrimalSharder());
const double dual_distance =
Distance(current_dual_solution_, last_dual_start_point_,
sharded_working_qp_.DualSharder());
// This choice of a nonzero tolerance balances performance and numerical
// issues caused by very huge or very tiny weights. It was picked as the best
// among {0.0, 1.0e-20, 2.0e-16, 1.0e-10, 1.0e-5} on the preprocessed MIPLIB
// dataset. The effect of changing this value is relatively minor overall.
constexpr double kNonzeroTol = 1.0e-10;
if (primal_distance <= kNonzeroTol || primal_distance >= 1.0 / kNonzeroTol ||
dual_distance <= kNonzeroTol || dual_distance >= 1.0 / kNonzeroTol) {
return primal_weight_;
}
const double smoothing_param = params_.primal_weight_update_smoothing();
const double unsmoothed_new_primal_weight = dual_distance / primal_distance;
const double new_primal_weight =
std::exp(smoothing_param * std::log(unsmoothed_new_primal_weight) +
(1.0 - smoothing_param) * std::log(primal_weight_));
LOG_IF(INFO, params_.verbosity_level() >= 4)
<< "New computed primal weight is " << new_primal_weight
<< " at iteration " << iterations_completed_;
return new_primal_weight;
}
SolverResult Solver::ConstructSolverResult(VectorXd primal_solution,
VectorXd dual_solution,
const IterationStats& stats,
TerminationReason termination_reason,
PointType output_type,
SolveLog solve_log) const {
switch (output_type) {
case POINT_TYPE_AVERAGE_ITERATE:
solve_log.set_solution_type(POINT_TYPE_AVERAGE_ITERATE);
break;
case POINT_TYPE_CURRENT_ITERATE:
AssignVector(current_primal_solution_,
sharded_working_qp_.PrimalSharder(), primal_solution);
AssignVector(current_dual_solution_, sharded_working_qp_.DualSharder(),
dual_solution);
solve_log.set_solution_type(POINT_TYPE_CURRENT_ITERATE);
break;
case POINT_TYPE_ITERATE_DIFFERENCE:
AssignVector(current_primal_delta_, sharded_working_qp_.PrimalSharder(),
primal_solution);
AssignVector(current_dual_delta_, sharded_working_qp_.DualSharder(),
dual_solution);
solve_log.set_solution_type(POINT_TYPE_ITERATE_DIFFERENCE);
break;
case POINT_TYPE_PRESOLVER_SOLUTION:
solve_log.set_solution_type(POINT_TYPE_PRESOLVER_SOLUTION);
break;
default:
// Default to average whenever the type is POINT_TYPE_NONE.
solve_log.set_solution_type(POINT_TYPE_AVERAGE_ITERATE);
break;
}
VectorXd reduced_costs;
const bool use_zero_primal_objective =
termination_reason == TERMINATION_REASON_PRIMAL_INFEASIBLE;
if (presolve_info_.has_value()) {
// Transform the solutions so they match the original unscaled problem.
PrimalAndDualSolution original_solution =
RecoverOriginalSolution({.primal_solution = std::move(primal_solution),
.dual_solution = std::move(dual_solution)});
primal_solution = std::move(original_solution.primal_solution);
dual_solution = std::move(original_solution.dual_solution);
// RecoverOriginalSolution doesn't recover reduced costs so we need to
// compute them with respect to the original problem.
reduced_costs =
ReducedCosts(presolve_info_->sharded_original_qp, primal_solution,
dual_solution, use_zero_primal_objective);
} else {
reduced_costs = ReducedCosts(sharded_working_qp_, primal_solution,
dual_solution, use_zero_primal_objective);
// Transform the solutions so they match the original unscaled problem.
CoefficientWiseProductInPlace(
col_scaling_vec_, sharded_working_qp_.PrimalSharder(), primal_solution);
CoefficientWiseProductInPlace(
row_scaling_vec_, sharded_working_qp_.DualSharder(), dual_solution);
CoefficientWiseQuotientInPlace(
col_scaling_vec_, sharded_working_qp_.PrimalSharder(), reduced_costs);
}
if (iteration_stats_callback_ != nullptr) {
iteration_stats_callback_(
{.termination_criteria = params_.termination_criteria(),
.iteration_stats = stats,
.bound_norms = original_bound_norms_});
}
if (params_.verbosity_level() >= 1) {
LOG(INFO) << "Termination reason: "
<< TerminationReason_Name(termination_reason);
LOG(INFO) << "Solution point type: " << PointType_Name(output_type);
LOG(INFO) << "Final solution stats:";
LOG(INFO) << IterationStatsLabelString();
LOG(INFO) << ToString(stats, params_.termination_criteria(),
original_bound_norms_, solve_log.solution_type());
const auto& convergence_info =
GetConvergenceInformation(stats, solve_log.solution_type());
if (convergence_info.has_value()) {
if (std::isfinite(convergence_info->corrected_dual_objective())) {
LOG(INFO) << "Dual objective after infeasibility correction: "
<< convergence_info->corrected_dual_objective();
}
}
}
solve_log.set_iteration_count(stats.iteration_number());
solve_log.set_termination_reason(termination_reason);
solve_log.set_solve_time_sec(stats.cumulative_time_sec());
*solve_log.mutable_solution_stats() = stats;
return SolverResult{.primal_solution = std::move(primal_solution),
.dual_solution = std::move(dual_solution),
.reduced_costs = std::move(reduced_costs),
.solve_log = std::move(solve_log)};
}
void SetActiveSetInformation(const ShardedQuadraticProgram& sharded_qp,
const VectorXd& primal_solution,
const VectorXd& dual_solution,
const VectorXd& primal_start_point,
const VectorXd& dual_start_point,
PointMetadata& metadata) {
CHECK_EQ(primal_solution.size(), sharded_qp.PrimalSize());
CHECK_EQ(dual_solution.size(), sharded_qp.DualSize());
CHECK_EQ(primal_start_point.size(), sharded_qp.PrimalSize());
CHECK_EQ(dual_start_point.size(), sharded_qp.DualSize());
const QuadraticProgram& qp = sharded_qp.Qp();
metadata.set_active_primal_variable_count(
static_cast<int64_t>(sharded_qp.PrimalSharder().ParallelSumOverShards(
[&](const Sharder::Shard& shard) {
const auto primal_shard = shard(primal_solution);
const auto lower_bound_shard = shard(qp.variable_lower_bounds);
const auto upper_bound_shard = shard(qp.variable_upper_bounds);
return (primal_shard.array() > lower_bound_shard.array() &&
primal_shard.array() < upper_bound_shard.array())
.count();
})));
// Most of the computation from the previous ParallelSumOverShards is
// duplicated here. However the overhead shouldn't be too large, and using
// ParallelSumOverShards is simpler than just using ParallelForEachShard.
metadata.set_active_primal_variable_change(
static_cast<int64_t>(sharded_qp.PrimalSharder().ParallelSumOverShards(
[&](const Sharder::Shard& shard) {
const auto primal_shard = shard(primal_solution);
const auto primal_start_shard = shard(primal_start_point);
const auto lower_bound_shard = shard(qp.variable_lower_bounds);
const auto upper_bound_shard = shard(qp.variable_upper_bounds);
return ((primal_shard.array() > lower_bound_shard.array() &&
primal_shard.array() < upper_bound_shard.array()) !=
(primal_start_shard.array() > lower_bound_shard.array() &&
primal_start_shard.array() < upper_bound_shard.array()))
.count();
})));
metadata.set_active_dual_variable_count(
static_cast<int64_t>(sharded_qp.DualSharder().ParallelSumOverShards(
[&](const Sharder::Shard& shard) {
const auto dual_shard = shard(dual_solution);
const auto lower_bound_shard = shard(qp.constraint_lower_bounds);
const auto upper_bound_shard = shard(qp.constraint_upper_bounds);
const double kInfinity = std::numeric_limits<double>::infinity();
return (dual_shard.array() != 0.0 ||
(lower_bound_shard.array() == -kInfinity &&
upper_bound_shard.array() == kInfinity))
.count();
})));
metadata.set_active_dual_variable_change(
static_cast<int64_t>(sharded_qp.DualSharder().ParallelSumOverShards(
[&](const Sharder::Shard& shard) {
const auto dual_shard = shard(dual_solution);
const auto dual_start_shard = shard(dual_start_point);
const auto lower_bound_shard = shard(qp.constraint_lower_bounds);
const auto upper_bound_shard = shard(qp.constraint_upper_bounds);
const double kInfinity = std::numeric_limits<double>::infinity();
return ((dual_shard.array() != 0.0 ||
(lower_bound_shard.array() == -kInfinity &&
upper_bound_shard.array() == kInfinity)) !=
(dual_start_shard.array() != 0.0 ||
(lower_bound_shard.array() == -kInfinity &&
upper_bound_shard.array() == kInfinity)))
.count();
})));
}
void Solver::AddConvergenceAndInfeasibilityInformation(