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