Optimist  0.0.0
A C++ library for optimization
Loading...
Searching...
No Matches
Adam.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
2 * Copyright (c) 2026, Davide Stocco and Enrico Bertolazzi. *
3 * *
4 * The Optimist project is distributed under the BSD 2-Clause License. *
5 * *
6 * Davide Stocco Enrico Bertolazzi *
7 * University of Trento University of Trento *
8 * davide.stocco@unitn.it enrico.bertolazzi@unitn.it *
9\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
10
11#pragma once
12
13#ifndef OPTIMIST_OPTIMIZER_ADAM_HH
14#define OPTIMIST_OPTIMIZER_ADAM_HH
15
16#include "Optimist/Optimizer.hh"
17
18namespace Optimist {
19
20 namespace Optimizer {
21
30 template <typename Vector>
31 requires TypeTrait<Vector>::IsEigen &&
32 (!TypeTrait<Vector>::IsFixed || TypeTrait<Vector>::Dimension > 0)
33 class Adam : public Optimizer<Vector, Adam<Vector>> {
34 public:
35 static constexpr bool RequiresFunction{true};
36 static constexpr bool RequiresFirstDerivative{true};
37 static constexpr bool RequiresSecondDerivative{false};
38
40 using Scalar = typename Vector::Scalar;
43
45
46 private:
50 Scalar m_epsilon{1.0e-8};
53 bool m_amsgrad{false};
54
55 public:
59 Adam() {
60 this->m_max_iterations = 10000;
61 this->m_max_function_evaluations = 10001;
63 }
64
68 constexpr std::string name_impl() const {
69 return this->m_amsgrad ? "AMSGrad" : "Adam";
70 }
71
76 return this->m_learning_rate;
77 }
78
82 void learning_rate(const Scalar t_learning_rate) {
83 OPTIMIST_ASSERT(t_learning_rate > 0,
84 "Optimist::Optimizer::Adam::learning_rate(...): "
85 "invalid input detected.");
86 this->m_learning_rate = t_learning_rate;
87 }
88
92 void betas(const Scalar t_beta_1, const Scalar t_beta_2) {
93 OPTIMIST_ASSERT(t_beta_1 >= 0 && t_beta_1 < 1 && t_beta_2 >= 0 &&
94 t_beta_2 < 1,
95 "Optimist::Optimizer::Adam::betas(...): invalid input "
96 "detected.");
97 this->m_beta_1 = t_beta_1;
98 this->m_beta_2 = t_beta_2;
99 }
100
105 void decay(const Scalar t_decay) {
106 OPTIMIST_ASSERT(t_decay >= 0,
107 "Optimist::Optimizer::Adam::decay(...): invalid input "
108 "detected.");
109 this->m_decay = t_decay;
110 }
111
115 void amsgrad_mode(const bool t_amsgrad) {
116 this->m_amsgrad = t_amsgrad;
117 }
118
127 template <typename FunctionLambda, typename GradientLambda>
128 bool solve_impl(FunctionLambda &&function,
129 GradientLambda &&gradient,
130 const Vector &x_ini,
131 Vector &x_sol) {
132#define CMD "Optimist::Optimizer::Adam::solve_impl(...): "
133
134 this->reset_counters();
135 if (this->m_verbose) {
136 this->header();
137 }
138
139 const Integer n{static_cast<Integer>(x_ini.size())};
140 Dense x(Utils::to_dense(x_ini)), g(n), m(Dense::Zero(n)),
141 v(Dense::Zero(n)), v_hat_max(Dense::Zero(n));
142 Dense x_best(x);
143 Scalar f, f_best{INFTY};
144
145 auto evaluate = [&](const Dense &z) -> bool {
146 const Vector zv{Utils::from_dense<Vector>(z)};
148 if (!this->evaluate_function(function, zv, f) ||
149 !this->evaluate_gradient(gradient, zv, gv)) {
150 return false;
151 }
152 g = Utils::to_dense(gv);
153 return std::isfinite(f) && g.allFinite();
154 };
155
156 Scalar beta_1_t{1}, beta_2_t{1};
157 std::string notes{"Initialize"};
158 try {
159 OPTIMIST_ASSERT(evaluate(x), CMD "evaluation failed.");
160 for (this->m_iterations = 1;
161 this->m_iterations < this->m_max_iterations;
162 ++this->m_iterations) {
163 if (f < f_best) {
164 f_best = f;
165 x_best = x;
166 }
167 const Scalar g_norm{g.norm()};
168 if (this->m_verbose && (this->m_iterations % 100 == 1)) {
169 this->info(g_norm, notes);
170 }
171 if (g_norm < this->m_tolerance) {
172 this->m_converged = true;
173 x_best = x;
174 break;
175 }
176
177 // Biased moment estimates and bias corrections
178 m = this->m_beta_1 * m + (1 - this->m_beta_1) * g;
179 v = this->m_beta_2 * v + (1 - this->m_beta_2) * g.cwiseAbs2();
180 beta_1_t *= this->m_beta_1;
181 beta_2_t *= this->m_beta_2;
182 const Dense m_hat{m / (1 - beta_1_t)};
183 Dense v_hat{v / (1 - beta_2_t)};
184 if (this->m_amsgrad) {
185 v_hat_max = v_hat_max.cwiseMax(v_hat);
186 v_hat = v_hat_max;
187 }
188
189 const Scalar eta{this->m_learning_rate /
190 (1 + this->m_decay * this->m_iterations)};
191 x -= eta * m_hat.cwiseQuotient(
192 (v_hat.cwiseSqrt().array() + this->m_epsilon).matrix());
193 OPTIMIST_ASSERT(evaluate(x), CMD "evaluation failed.");
194 notes = "-";
195 }
196 } catch (const std::runtime_error &) {
197 notes = "Budget exhausted";
198 }
199
200 if (this->m_verbose) {
201 this->bottom();
202 }
203 x_sol = Utils::from_dense<Vector>(x_best);
204 return this->m_converged;
205
206#undef CMD
207 }
208
209 }; // class Adam
210
211 } // namespace Optimizer
212
213} // namespace Optimist
214
215#endif // OPTIMIST_OPTIMIZER_ADAM_HH
#define CMD
#define OPTIMIST_BASIC_CONSTANTS(Scalar)
Definition Optimist.hh:70
#define OPTIMIST_ASSERT(COND, MSG)
Definition Optimist.hh:48
bool solve_impl(FunctionLambda &&function, GradientLambda &&gradient, const Vector &x_ini, Vector &x_sol)
Definition Adam.hh:128
void amsgrad_mode(const bool t_amsgrad)
Definition Adam.hh:115
void decay(const Scalar t_decay)
Definition Adam.hh:105
Scalar m_decay
Definition Adam.hh:51
static constexpr bool RequiresFirstDerivative
Definition Adam.hh:36
Scalar m_beta_1
Definition Adam.hh:48
Scalar m_epsilon
Definition Adam.hh:50
Scalar m_beta_2
Definition Adam.hh:49
Scalar learning_rate() const
Definition Adam.hh:75
void betas(const Scalar t_beta_1, const Scalar t_beta_2)
Definition Adam.hh:92
bool m_amsgrad
Definition Adam.hh:53
static constexpr bool RequiresFunction
Definition Adam.hh:35
TypeTrait< Vector > VectorTrait
Definition Adam.hh:39
Adam()
Definition Adam.hh:59
typename Vector::Scalar Scalar
Definition Adam.hh:40
void learning_rate(const Scalar t_learning_rate)
Definition Adam.hh:82
constexpr std::string name_impl() const
Definition Adam.hh:68
Utils::DenseVector< Vector > Dense
Definition Adam.hh:41
Scalar m_learning_rate
Definition Adam.hh:47
static constexpr bool RequiresSecondDerivative
Definition Adam.hh:37
bool evaluate_gradient(GradientLambda &&gradient, const Input &x, FirstDerivative &out)
Definition Optimizer.hh:128
void info(Scalar residuals, const std::string &notes="-")
Definition SolverBase.hh:1218
bool evaluate_function(FunctionLambda &&function, const Vector &x, TypeTrait< Vector >::Scalar &out)
Definition SolverBase.hh:1026
FunctionBase< Vector, TypeTrait< Vector >::Scalar, Adam< Vector > >::FirstDerivative FirstDerivative
Definition SolverBase.hh:72
Vector from_dense(const Eigen::MatrixBase< Derived > &x)
Definition Utils.hh:59
Eigen::Matrix< typename TypeTrait< Vector >::Scalar, Eigen::Dynamic, 1 > DenseVector
Definition Utils.hh:31
DenseVector< Vector > to_dense(const Vector &x)
Definition Utils.hh:48
Namespace for the Optimist library.
Definition Optimist.hh:90
OPTIMIST_DEFAULT_INTEGER_TYPE Integer
The Integer type as used for the API.
Definition Optimist.hh:98
Definition Optimist.hh:105