alpaqa 1.0.0a9
Nonconvex constrained optimization
Loading...
Searching...
No Matches
zerofpr.tpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <cassert>
6#include <cmath>
7#include <iomanip>
8#include <iostream>
9#include <stdexcept>
10
15#include <alpaqa/util/timed.hpp>
16
17namespace alpaqa {
18
19template <class DirectionProviderT>
21 return "ZeroFPRSolver<" + std::string(direction.get_name()) + ">";
22}
23
24template <class DirectionProviderT>
26 /// [in] Problem description
27 const Problem &problem,
28 /// [in] Solve options
29 const SolveOptions &opts,
30 /// [inout] Decision variable @f$ x @f$
31 rvec x,
32 /// [inout] Lagrange multipliers @f$ y @f$
33 rvec y,
34 /// [in] Constraint weights @f$ \Sigma @f$
35 crvec Σ,
36 /// [out] Slack variable error @f$ g(x) - \Pi_D(g(x) + \Sigma^{-1} y) @f$
37 rvec err_z) -> Stats {
38
39 if (opts.check)
40 problem.check();
41
42 using std::chrono::nanoseconds;
43 auto os = opts.os ? opts.os : this->os;
44 auto start_time = std::chrono::steady_clock::now();
45 Stats s;
46
47 const auto n = problem.get_n();
48 const auto m = problem.get_m();
49
50 // Represents an intermediate proximal iterate in the algorithm.
51 struct ProxIterate {
52 vec x̂; //< Decision variables after proximal gradient step
53 vec grad_ψ; //< Gradient of cost in x
54 vec p; //< Proximal gradient step in x
55 vec ŷx̂; //< Candidate Lagrange multipliers in x̂
56 real_t pᵀp = NaN<config_t>; //< Norm squared of p
57 real_t grad_ψᵀp = NaN<config_t>; //< Dot product of gradient and p
58 real_t hx̂ = NaN<config_t>; //< Non-smooth function value in x̂
59
60 ProxIterate(length_t n, length_t m) : x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
61 } prox_iterate{n, m};
62 // Represents an iterate in the algorithm, keeping track of some
63 // intermediate values and function evaluations.
64 struct Iterate {
65 vec x; //< Decision variables
66 vec x̂; //< Decision variables after proximal gradient step
67 vec grad_ψ; //< Gradient of cost in x
68 vec p; //< Proximal gradient step in x
69 vec ŷx̂; //< Candidate Lagrange multipliers in x̂
70 real_t ψx = NaN<config_t>; //< Cost in x
71 real_t ψx̂ = NaN<config_t>; //< Cost in x̂
72 real_t γ = NaN<config_t>; //< Step size γ
73 real_t L = NaN<config_t>; //< Lipschitz estimate L
74 real_t pᵀp = NaN<config_t>; //< Norm squared of p
75 real_t grad_ψᵀp = NaN<config_t>; //< Dot product of gradient and p
76 real_t hx̂ = NaN<config_t>; //< Non-smooth function value in x̂
77
78 // @pre @ref ψx, @ref hx̂ @ref pᵀp, @ref grad_ψᵀp
79 // @return φγ
80 real_t fbe() const { return ψx + hx̂ + pᵀp / (2 * γ) + grad_ψᵀp; }
81
82 Iterate(length_t n, length_t m) : x(n), x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
83 } iterates[2]{{n, m}, {n, m}};
84 Iterate *curr = &iterates[0];
85 ProxIterate *prox = &prox_iterate;
86 Iterate *next = &iterates[1];
87
88 vec work_n(n), work_m(m);
89 vec q(n); // (quasi-)Newton step Hₖ pₖ
90
91 // Helper functions --------------------------------------------------------
92
93 auto qub_violated = [this](const Iterate &i) {
94 real_t margin =
95 (1 + std::abs(i.ψx)) * params.quadratic_upperbound_tolerance_factor;
96 return i.ψx̂ > i.ψx + i.grad_ψᵀp + real_t(0.5) * i.L * i.pᵀp + margin;
97 };
98
99 auto linesearch_violated = [this](const Iterate &curr,
100 const Iterate &next) {
101 if (params.force_linesearch)
102 return false;
103 real_t β = params.linesearch_strictness_factor;
104 real_t σ = β * (1 - curr.γ * curr.L) / (2 * curr.γ);
105 real_t φγ = curr.fbe();
106 real_t margin = (1 + std::abs(φγ)) * params.linesearch_tolerance_factor;
107 return next.fbe() > φγ - σ * curr.pᵀp + margin;
108 };
109
110 // Problem functions -------------------------------------------------------
111
112 auto eval_ψ_grad_ψ = [&problem, &y, &Σ, &work_n, &work_m](Iterate &i) {
113 i.ψx = problem.eval_ψ_grad_ψ(i.x, y, Σ, i.grad_ψ, work_n, work_m);
114 };
115 auto eval_prox_grad_step = [&problem](Iterate &i) {
116 i.hx̂ = problem.eval_prox_grad_step(i.γ, i.x, i.grad_ψ, i.x̂, i.p);
117 i.pᵀp = i.p.squaredNorm();
118 i.grad_ψᵀp = i.p.dot(i.grad_ψ);
119 };
120 auto eval_cost_in_prox = [&problem, &y, &Σ](Iterate &i) {
121 i.ψx̂ = problem.eval_ψ(i.x̂, y, Σ, i.ŷx̂);
122 };
123 auto eval_grad_in_prox = [&problem, &prox, &work_n](const Iterate &i) {
124 problem.eval_grad_L(i.x̂, i.ŷx̂, prox->grad_ψ, work_n);
125 };
126 auto eval_prox_grad_step_in_prox = [&problem, &prox](const Iterate &i) {
127 prox->hx̂ = problem.eval_prox_grad_step(i.γ, i.x̂, prox->grad_ψ, prox->x̂,
128 prox->p);
129 prox->pᵀp = prox->p.squaredNorm();
130 prox->grad_ψᵀp = prox->p.dot(prox->grad_ψ);
131 };
132
133 // Printing ----------------------------------------------------------------
134
135 std::array<char, 64> print_buf;
136 auto print_real = [this, &print_buf](real_t x) {
137 return float_to_str_vw(print_buf, x, params.print_precision);
138 };
139 auto print_real3 = [&print_buf](real_t x) {
140 return float_to_str_vw(print_buf, x, 3);
141 };
142 auto print_progress_1 = [&print_real, os](unsigned k, real_t φₖ, real_t ψₖ,
143 crvec grad_ψₖ, real_t pₖᵀpₖ,
144 real_t γₖ, real_t εₖ) {
145 if (k == 0)
146 *os << "┌─[ZeroFPR]\n";
147 else
148 *os << "├─ " << std::setw(6) << k << '\n';
149 *os << "│ φγ = " << print_real(φₖ) //
150 << ", ψ = " << print_real(ψₖ) //
151 << ", ‖∇ψ‖ = " << print_real(grad_ψₖ.norm()) //
152 << ", ‖p‖ = " << print_real(std::sqrt(pₖᵀpₖ)) //
153 << ", γ = " << print_real(γₖ) //
154 << ", ε = " << print_real(εₖ) << '\n';
155 };
156 auto print_progress_2 = [&print_real, &print_real3, os](crvec qₖ, real_t τₖ,
157 bool reject) {
158 const char *color = τₖ == 1 ? "\033[0;32m"
159 : τₖ > 0 ? "\033[0;33m"
160 : "\033[0;35m";
161 *os << "│ ‖q‖ = " << print_real(qₖ.norm()) //
162 << ", τ = " << color << print_real3(τₖ) << "\033[0m" //
163 << ", dir update "
164 << (reject ? "\033[0;31mrejected\033[0m"
165 : "\033[0;32maccepted\033[0m") //
166 << std::endl; // Flush for Python buffering
167 };
168 auto print_progress_n = [&](SolverStatus status) {
169 *os << "└─ " << status << " ──"
170 << std::endl; // Flush for Python buffering
171 };
172
173 auto do_progress_cb = [this, &s, &problem, &Σ, &y, &opts](
174 unsigned k, Iterate &it, crvec q, crvec grad_ψx̂,
175 real_t τ, real_t εₖ, SolverStatus status) {
176 if (!progress_cb)
177 return;
180 progress_cb(ProgressInfo{
181 .k = k,
182 .status = status,
183 .x = it.x,
184 .p = it.p,
185 .norm_sq_p = it.pᵀp,
186 .x̂ = it.x̂,
187 .φγ = it.fbe(),
188 .ψ = it.ψx,
189 .grad_ψ = it.grad_ψ,
190 .ψ_hat = it.ψx̂,
191 .grad_ψ_hat = grad_ψx̂,
192 .q = q,
193 .L = it.L,
194 .γ = it.γ,
195 .τ = τ,
196 .ε = εₖ,
197 .Σ = Σ,
198 .y = y,
199 .outer_iter = opts.outer_iter,
200 .problem = &problem,
201 .params = &params,
202 });
203 };
204
205 // Initialization ----------------------------------------------------------
206
207 curr->x = x;
208
209 // Estimate Lipschitz constant ---------------------------------------------
210
211 // Finite difference approximation of ∇²ψ in starting point
212 if (params.Lipschitz.L_0 <= 0) {
213 curr->L = Helpers::initial_lipschitz_estimate(
214 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
215 params.L_min, params.L_max,
216 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, next->grad_ψ,
217 work_n, work_m);
218 }
219 // Initial Lipschitz constant provided by the user
220 else {
221 curr->L = params.Lipschitz.L_0;
222 // Calculate ψ(xₖ), ∇ψ(x₀)
223 eval_ψ_grad_ψ(*curr);
224 }
225 if (not std::isfinite(curr->L)) {
227 return s;
228 }
229 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
230
231 // First proximal gradient step --------------------------------------------
232
233 // Calculate x̂ₖ, ψ(x̂ₖ)
234 eval_prox_grad_step(*curr);
235 eval_cost_in_prox(*curr);
236
237 // Quadratic upper bound
238 while (curr->L < params.L_max && qub_violated(*curr)) {
239 curr->γ /= 2;
240 curr->L *= 2;
241 eval_prox_grad_step(*curr);
242 eval_cost_in_prox(*curr);
243 }
244
245 // Loop data ---------------------------------------------------------------
246
247 unsigned k = 0; // iteration
248 real_t τ = NaN<config_t>; // line search parameter
249 // Keep track of how many successive iterations didn't update the iterate
250 unsigned no_progress = 0;
251
252 // Main ZeroFPR loop
253 // =========================================================================
254
255 ScopedMallocBlocker mb; // Don't allocate in the inner loop
256 while (true) {
257
258 // Check stopping criteria ---------------------------------------------
259
260 // Calculate ∇ψ(x̂ₖ), p̂ₖ
261 eval_grad_in_prox(*curr);
262 eval_prox_grad_step_in_prox(*curr);
263
264 real_t εₖ = Helpers::calc_error_stop_crit(
265 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
266 curr->ŷx̂, curr->grad_ψ, prox->grad_ψ, work_n, next->p);
267
268 // Print progress ------------------------------------------------------
269 bool do_print =
270 params.print_interval != 0 && k % params.print_interval == 0;
271 if (do_print)
272 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
273 curr->γ, εₖ);
274
275 // Return solution -----------------------------------------------------
276
277 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
278 auto stop_status = Helpers::check_all_stop_conditions(
279 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
280 if (stop_status != SolverStatus::Busy) {
281 do_progress_cb(k, *curr, null_vec<config_t>, prox->grad_ψ, -1, εₖ,
282 stop_status);
283 bool do_final_print = params.print_interval != 0;
284 if (!do_print && do_final_print)
285 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
286 curr->pᵀp, curr->γ, εₖ);
287 if (do_print || do_final_print)
288 print_progress_n(stop_status);
289 if (stop_status == SolverStatus::Converged ||
290 stop_status == SolverStatus::Interrupted ||
291 opts.always_overwrite_results) {
292 auto &ŷ = curr->ŷx̂;
293 if (err_z.size() > 0)
294 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
295 x = std::move(curr->x̂);
296 y = std::move(curr->ŷx̂);
297 }
298 s.iterations = k;
299 s.ε = εₖ;
300 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
301 s.status = stop_status;
302 s.final_γ = curr->γ;
303 s.final_ψ = curr->ψx̂;
304 s.final_h = curr->hx̂;
305 s.final_φγ = curr->fbe();
306 return s;
307 }
308
309 // Calculate quasi-Newton step -----------------------------------------
310
311 real_t τ_init = NaN<config_t>;
312 if (k == 0) { // Initialize L-BFGS
314 direction.initialize(problem, y, Σ, curr->γ, curr->x̂, prox->x̂,
315 prox->p, prox->grad_ψ);
316 τ_init = 0;
317 }
318 if (k > 0 || direction.has_initial_direction()) {
319 τ_init = direction.apply(curr->γ, curr->x̂, prox->x̂, prox->p,
320 prox->grad_ψ, q)
321 ? 1
322 : 0;
323 // Make sure quasi-Newton step is valid
324 if (τ_init == 1 && not q.allFinite())
325 τ_init = 0;
326 if (τ_init != 1) { // If we computed a quasi-Newton step
327 ++s.lbfgs_failures;
328 direction.reset(); // Is there anything else we can do?
329 }
330 }
331
332 // Line search ---------------------------------------------------------
333
334 next->γ = curr->γ;
335 next->L = curr->L;
336 τ = τ_init;
337 real_t τ_prev = -1;
338 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
339 bool updated_lbfgs = false;
340 bool dir_rejected = true;
341
342 // xₖ₊₁ = xₖ + pₖ
343 auto take_safe_step = [&] {
344 next->x = curr->x̂; // → safe prox step
345 next->ψx = curr->ψx̂;
346 next->grad_ψ = prox->grad_ψ;
347 // TODO: could swap gradients, but need for direction update
348 };
349
350 // xₖ₊₁ = x̂ₖ + τ qₖ
351 auto take_accelerated_step = [&](real_t τ) {
352 if (τ == 1) // → faster quasi-Newton step
353 next->x = curr->x̂ + q;
354 else
355 next->x = curr->x̂ + τ * q;
356 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
357 eval_ψ_grad_ψ(*next);
358 };
359
360 while (!stop_signal.stop_requested()) {
361
362 // Recompute step only if τ changed
363 if (τ != τ_prev) {
364 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
365 τ_prev = τ;
366 }
367
368 // If the cost is not finite, or if the quadratic upper bound could
369 // not be satisfied, abandon the direction entirely, don't even
370 // bother backtracking.
371 bool fail = next->L >= params.L_max || !std::isfinite(next->ψx);
372 if (τ > 0 && fail) {
373 // Don't allow a bad accelerated step to destroy the FBS step
374 // size
375 next->L = curr->L;
376 next->γ = curr->γ;
377 // Line search failed
378 τ = 0;
379 direction.reset();
380 // Update the direction in the FB iterate later
381 update_lbfgs_in_linesearch = false;
382 continue;
383 }
384
385 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
386 eval_prox_grad_step(*next);
387 eval_cost_in_prox(*next);
388
389 // Quadratic upper bound step size condition
390 if (next->L < params.L_max && qub_violated(*next)) {
391 next->γ /= 2;
392 next->L *= 2;
393 if (τ > 0)
394 τ = τ_init;
396 // If the step size changes, we need extra care when updating
397 // the direction later
398 update_lbfgs_in_linesearch = false;
399 continue;
400 }
401
402 // Update L-BFGS
403 if (update_lbfgs_in_linesearch && !updated_lbfgs) {
404 if (params.update_direction_from_prox_step) {
405 s.lbfgs_rejected += dir_rejected = not direction.update(
406 curr->γ, next->γ, curr->x̂, next->x, prox->p, next->p,
407 prox->grad_ψ, next->grad_ψ);
408 } else {
409 s.lbfgs_rejected += dir_rejected = not direction.update(
410 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
411 curr->grad_ψ, next->grad_ψ);
412 }
413 update_lbfgs_in_linesearch = false;
414 updated_lbfgs = true;
415 }
416
417 // Line search condition
418 if (τ > 0 && linesearch_violated(*curr, *next)) {
419 τ /= 2;
420 if (τ < params.min_linesearch_coefficient)
421 τ = 0;
423 continue;
424 }
425
426 // QUB and line search satisfied (or τ is 0 and L > L_max)
427 break;
428 }
429 // If τ < τ_min the line search failed and we accepted the prox step
430 s.linesearch_failures += (τ == 0 && τ_init > 0);
431 s.τ_1_accepted += τ == 1;
432 s.count_τ += (τ_init > 0);
433 s.sum_τ += τ;
434
435 // Check if we made any progress
436 if (no_progress > 0 || k % params.max_no_progress == 0)
437 no_progress = curr->x == next->x ? no_progress + 1 : 0;
438
439 // Update L-BFGS -------------------------------------------------------
440
441 if (!updated_lbfgs) {
442 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
443 direction.changed_γ(next->γ, curr->γ);
444 if (params.recompute_last_prox_step_after_lbfgs_flush) {
445 curr->γ = next->γ;
446 curr->L = next->L;
447 eval_prox_grad_step_in_prox(*curr);
448 }
449 }
450 if (τ > 0 && params.update_direction_from_prox_step) {
451 s.lbfgs_rejected += dir_rejected = not direction.update(
452 curr->γ, next->γ, curr->x̂, next->x, prox->p, next->p,
453 prox->grad_ψ, next->grad_ψ);
454 } else {
455 s.lbfgs_rejected += dir_rejected = not direction.update(
456 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
457 curr->grad_ψ, next->grad_ψ);
458 }
459 }
460
461 // Print ---------------------------------------------------------------
462 do_progress_cb(k, *curr, q, prox->grad_ψ, τ, εₖ, SolverStatus::Busy);
463 if (do_print && (k != 0 || direction.has_initial_direction()))
464 print_progress_2(q, τ, dir_rejected);
465
466 // Advance step --------------------------------------------------------
467 std::swap(curr, next);
468 ++k;
469
470#ifndef NDEBUG
471 {
473 *prox = {n, m};
474 *next = {n, m};
475 }
476#endif
477 }
478 throw std::logic_error("[ZeroFPR] loop error");
479}
480
481} // namespace alpaqa
std::string get_name() const
Definition: zerofpr.tpp:20
Stats operator()(const Problem &problem, const SolveOptions &opts, rvec x, rvec y, crvec Σ, rvec err_z)
Definition: zerofpr.tpp:25
unsigned stepsize_backtracks
Definition: zerofpr.hpp:76
unsigned lbfgs_rejected
Definition: zerofpr.hpp:78
unsigned τ_1_accepted
Definition: zerofpr.hpp:79
unsigned lbfgs_failures
Definition: zerofpr.hpp:77
SolverStatus
Exit status of a numerical solver such as ALM or PANOC.
@ Interrupted
Solver was interrupted by the user.
@ Busy
In progress.
@ Converged
Converged and reached given tolerance.
@ NotFinite
Intermediate results were infinite or not-a-number.
std::chrono::nanoseconds time_progress_callback
Definition: zerofpr.hpp:72
std::chrono::nanoseconds elapsed_time
Definition: zerofpr.hpp:71
typename Conf::real_t real_t
Definition: config.hpp:63
unsigned linesearch_backtracks
Definition: zerofpr.hpp:75
typename Conf::length_t length_t
Definition: config.hpp:74
typename Conf::rvec rvec
Definition: config.hpp:67
std::string_view float_to_str_vw(auto &buf, double value, int precision=std::numeric_limits< double >::max_digits10)
Definition: print.tpp:39
typename Conf::crvec crvec
Definition: config.hpp:68
unsigned linesearch_failures
Definition: zerofpr.hpp:74
typename Conf::vec vec
Definition: config.hpp:64
unsigned iterations
Definition: zerofpr.hpp:73
SolverStatus status
Definition: zerofpr.hpp:69