trust_region_minimizer.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2016 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: sameeragarwal@google.com (Sameer Agarwal)
  30. #include "ceres/trust_region_minimizer.h"
  31. #include <algorithm>
  32. #include <cmath>
  33. #include <cstdlib>
  34. #include <cstring>
  35. #include <limits>
  36. #include <memory>
  37. #include <string>
  38. #include <vector>
  39. #include "Eigen/Core"
  40. #include "ceres/array_utils.h"
  41. #include "ceres/coordinate_descent_minimizer.h"
  42. #include "ceres/eigen_vector_ops.h"
  43. #include "ceres/evaluator.h"
  44. #include "ceres/file.h"
  45. #include "ceres/line_search.h"
  46. #include "ceres/parallel_for.h"
  47. #include "ceres/stringprintf.h"
  48. #include "ceres/types.h"
  49. #include "ceres/wall_time.h"
  50. #include "glog/logging.h"
  51. // Helper macro to simplify some of the control flow.
  52. #define RETURN_IF_ERROR_AND_LOG(expr) \
  53. do { \
  54. if (!(expr)) { \
  55. LOG(ERROR) << "Terminating: " << solver_summary_->message; \
  56. return; \
  57. } \
  58. } while (0)
  59. namespace ceres::internal {
  60. void TrustRegionMinimizer::Minimize(const Minimizer::Options& options,
  61. double* parameters,
  62. Solver::Summary* solver_summary) {
  63. start_time_in_secs_ = WallTimeInSeconds();
  64. iteration_start_time_in_secs_ = start_time_in_secs_;
  65. Init(options, parameters, solver_summary);
  66. RETURN_IF_ERROR_AND_LOG(IterationZero());
  67. // Create the TrustRegionStepEvaluator. The construction needs to be
  68. // delayed to this point because we need the cost for the starting
  69. // point to initialize the step evaluator.
  70. step_evaluator_ = std::make_unique<TrustRegionStepEvaluator>(
  71. x_cost_,
  72. options_.use_nonmonotonic_steps
  73. ? options_.max_consecutive_nonmonotonic_steps
  74. : 0);
  75. bool atleast_one_successful_step = false;
  76. while (FinalizeIterationAndCheckIfMinimizerCanContinue()) {
  77. iteration_start_time_in_secs_ = WallTimeInSeconds();
  78. const double previous_gradient_norm = iteration_summary_.gradient_norm;
  79. const double previous_gradient_max_norm =
  80. iteration_summary_.gradient_max_norm;
  81. iteration_summary_ = IterationSummary();
  82. iteration_summary_.iteration =
  83. solver_summary->iterations.back().iteration + 1;
  84. RETURN_IF_ERROR_AND_LOG(ComputeTrustRegionStep());
  85. if (!iteration_summary_.step_is_valid) {
  86. RETURN_IF_ERROR_AND_LOG(HandleInvalidStep());
  87. continue;
  88. }
  89. if (options_.is_constrained &&
  90. options_.max_num_line_search_step_size_iterations > 0) {
  91. // Use a projected line search to enforce the bounds constraints
  92. // and improve the quality of the step.
  93. DoLineSearch(x_, gradient_, x_cost_, &delta_);
  94. }
  95. ComputeCandidatePointAndEvaluateCost();
  96. DoInnerIterationsIfNeeded();
  97. if (atleast_one_successful_step && ParameterToleranceReached()) {
  98. return;
  99. }
  100. if (FunctionToleranceReached()) {
  101. return;
  102. }
  103. if (IsStepSuccessful()) {
  104. atleast_one_successful_step = true;
  105. RETURN_IF_ERROR_AND_LOG(HandleSuccessfulStep());
  106. } else {
  107. // Declare the step unsuccessful and inform the trust region strategy.
  108. iteration_summary_.step_is_successful = false;
  109. iteration_summary_.cost = candidate_cost_ + solver_summary_->fixed_cost;
  110. // When the step is unsuccessful, we do not compute the gradient
  111. // (or update x), so we preserve its value from the last
  112. // successful iteration.
  113. iteration_summary_.gradient_norm = previous_gradient_norm;
  114. iteration_summary_.gradient_max_norm = previous_gradient_max_norm;
  115. strategy_->StepRejected(iteration_summary_.relative_decrease);
  116. }
  117. }
  118. }
  119. // Initialize the minimizer, allocate working space and set some of
  120. // the fields in the solver_summary.
  121. void TrustRegionMinimizer::Init(const Minimizer::Options& options,
  122. double* parameters,
  123. Solver::Summary* solver_summary) {
  124. options_ = options;
  125. std::sort(options_.trust_region_minimizer_iterations_to_dump.begin(),
  126. options_.trust_region_minimizer_iterations_to_dump.end());
  127. parameters_ = parameters;
  128. solver_summary_ = solver_summary;
  129. solver_summary_->termination_type = NO_CONVERGENCE;
  130. solver_summary_->num_successful_steps = 0;
  131. solver_summary_->num_unsuccessful_steps = 0;
  132. solver_summary_->is_constrained = options.is_constrained;
  133. CHECK(options_.evaluator != nullptr);
  134. CHECK(options_.jacobian != nullptr);
  135. CHECK(options_.trust_region_strategy != nullptr);
  136. evaluator_ = options_.evaluator.get();
  137. jacobian_ = options_.jacobian.get();
  138. strategy_ = options_.trust_region_strategy.get();
  139. is_not_silent_ = !options.is_silent;
  140. inner_iterations_are_enabled_ =
  141. options.inner_iteration_minimizer.get() != nullptr;
  142. inner_iterations_were_useful_ = false;
  143. num_parameters_ = evaluator_->NumParameters();
  144. num_effective_parameters_ = evaluator_->NumEffectiveParameters();
  145. num_residuals_ = evaluator_->NumResiduals();
  146. num_consecutive_invalid_steps_ = 0;
  147. x_ = ConstVectorRef(parameters_, num_parameters_);
  148. residuals_.resize(num_residuals_);
  149. trust_region_step_.resize(num_effective_parameters_);
  150. delta_.resize(num_effective_parameters_);
  151. candidate_x_.resize(num_parameters_);
  152. gradient_.resize(num_effective_parameters_);
  153. model_residuals_.resize(num_residuals_);
  154. negative_gradient_.resize(num_effective_parameters_);
  155. projected_gradient_step_.resize(num_parameters_);
  156. // By default scaling is one, if the user requests Jacobi scaling of
  157. // the Jacobian, we will compute and overwrite this vector.
  158. jacobian_scaling_ = Vector::Ones(num_effective_parameters_);
  159. x_cost_ = std::numeric_limits<double>::max();
  160. minimum_cost_ = x_cost_;
  161. model_cost_change_ = 0.0;
  162. }
  163. // 1. Project the initial solution onto the feasible set if needed.
  164. // 2. Compute the initial cost, jacobian & gradient.
  165. //
  166. // Return true if all computations can be performed successfully.
  167. bool TrustRegionMinimizer::IterationZero() {
  168. iteration_summary_ = IterationSummary();
  169. iteration_summary_.iteration = 0;
  170. iteration_summary_.step_is_valid = false;
  171. iteration_summary_.step_is_successful = false;
  172. iteration_summary_.cost_change = 0.0;
  173. iteration_summary_.gradient_max_norm = 0.0;
  174. iteration_summary_.gradient_norm = 0.0;
  175. iteration_summary_.step_norm = 0.0;
  176. iteration_summary_.relative_decrease = 0.0;
  177. iteration_summary_.eta = options_.eta;
  178. iteration_summary_.linear_solver_iterations = 0;
  179. iteration_summary_.step_solver_time_in_seconds = 0;
  180. if (options_.is_constrained) {
  181. delta_.setZero();
  182. if (!evaluator_->Plus(x_.data(), delta_.data(), candidate_x_.data())) {
  183. solver_summary_->message =
  184. "Unable to project initial point onto the feasible set.";
  185. solver_summary_->termination_type = FAILURE;
  186. return false;
  187. }
  188. x_ = candidate_x_;
  189. }
  190. if (!EvaluateGradientAndJacobian(/*new_evaluation_point=*/true)) {
  191. return false;
  192. }
  193. solver_summary_->initial_cost = x_cost_ + solver_summary_->fixed_cost;
  194. iteration_summary_.step_is_valid = true;
  195. iteration_summary_.step_is_successful = true;
  196. return true;
  197. }
  198. // For the current x_, compute
  199. //
  200. // 1. Cost
  201. // 2. Jacobian
  202. // 3. Gradient
  203. // 4. Scale the Jacobian if needed (and compute the scaling if we are
  204. // in iteration zero).
  205. // 5. Compute the 2 and max norm of the gradient.
  206. //
  207. // Returns true if all computations could be performed
  208. // successfully. Any failures are considered fatal and the
  209. // Solver::Summary is updated to indicate this.
  210. bool TrustRegionMinimizer::EvaluateGradientAndJacobian(
  211. bool new_evaluation_point) {
  212. Evaluator::EvaluateOptions evaluate_options;
  213. evaluate_options.new_evaluation_point = new_evaluation_point;
  214. if (!evaluator_->Evaluate(evaluate_options,
  215. x_.data(),
  216. &x_cost_,
  217. residuals_.data(),
  218. gradient_.data(),
  219. jacobian_)) {
  220. solver_summary_->message = "Residual and Jacobian evaluation failed.";
  221. solver_summary_->termination_type = FAILURE;
  222. return false;
  223. }
  224. iteration_summary_.cost = x_cost_ + solver_summary_->fixed_cost;
  225. if (options_.jacobi_scaling) {
  226. if (iteration_summary_.iteration == 0) {
  227. // Compute a scaling vector that is used to improve the
  228. // conditioning of the Jacobian.
  229. //
  230. // jacobian_scaling_ = diag(J'J)^{-1}
  231. jacobian_->SquaredColumnNorm(jacobian_scaling_.data());
  232. for (int i = 0; i < jacobian_->num_cols(); ++i) {
  233. // Add one to the denominator to prevent division by zero.
  234. jacobian_scaling_[i] = 1.0 / (1.0 + sqrt(jacobian_scaling_[i]));
  235. }
  236. }
  237. // jacobian = jacobian * diag(J'J) ^{-1}
  238. jacobian_->ScaleColumns(
  239. jacobian_scaling_.data(), options_.context, options_.num_threads);
  240. }
  241. // The gradient exists in the local tangent space. To account for
  242. // the bounds constraints correctly, instead of just computing the
  243. // norm of the gradient vector, we compute
  244. //
  245. // |Plus(x, -gradient) - x|
  246. //
  247. // Where the Plus operator lifts the negative gradient to the
  248. // ambient space, adds it to x and projects it on the hypercube
  249. // defined by the bounds.
  250. negative_gradient_ = -gradient_;
  251. if (!evaluator_->Plus(x_.data(),
  252. negative_gradient_.data(),
  253. projected_gradient_step_.data())) {
  254. solver_summary_->message =
  255. "projected_gradient_step = Plus(x, -gradient) failed.";
  256. solver_summary_->termination_type = FAILURE;
  257. return false;
  258. }
  259. iteration_summary_.gradient_max_norm =
  260. (x_ - projected_gradient_step_).lpNorm<Eigen::Infinity>();
  261. iteration_summary_.gradient_norm = (x_ - projected_gradient_step_).norm();
  262. return true;
  263. }
  264. // 1. Add the final timing information to the iteration summary.
  265. // 2. Run the callbacks
  266. // 3. Check for termination based on
  267. // a. Run time
  268. // b. Iteration count
  269. // c. Max norm of the gradient
  270. // d. Size of the trust region radius.
  271. //
  272. // Returns true if user did not terminate the solver and none of these
  273. // termination criterion are met.
  274. bool TrustRegionMinimizer::FinalizeIterationAndCheckIfMinimizerCanContinue() {
  275. if (iteration_summary_.step_is_successful) {
  276. ++solver_summary_->num_successful_steps;
  277. if (x_cost_ < minimum_cost_) {
  278. minimum_cost_ = x_cost_;
  279. VectorRef(parameters_, num_parameters_) = x_;
  280. iteration_summary_.step_is_nonmonotonic = false;
  281. } else {
  282. iteration_summary_.step_is_nonmonotonic = true;
  283. }
  284. } else {
  285. ++solver_summary_->num_unsuccessful_steps;
  286. }
  287. iteration_summary_.trust_region_radius = strategy_->Radius();
  288. iteration_summary_.iteration_time_in_seconds =
  289. WallTimeInSeconds() - iteration_start_time_in_secs_;
  290. iteration_summary_.cumulative_time_in_seconds =
  291. WallTimeInSeconds() - start_time_in_secs_ +
  292. solver_summary_->preprocessor_time_in_seconds;
  293. solver_summary_->iterations.push_back(iteration_summary_);
  294. if (!RunCallbacks(options_, iteration_summary_, solver_summary_)) {
  295. return false;
  296. }
  297. if (MaxSolverTimeReached()) {
  298. return false;
  299. }
  300. if (MaxSolverIterationsReached()) {
  301. return false;
  302. }
  303. if (GradientToleranceReached()) {
  304. return false;
  305. }
  306. if (MinTrustRegionRadiusReached()) {
  307. return false;
  308. }
  309. return true;
  310. }
  311. // Compute the trust region step using the TrustRegionStrategy chosen
  312. // by the user.
  313. //
  314. // If the strategy returns with LinearSolverTerminationType::FATAL_ERROR, which
  315. // indicates an unrecoverable error, return false. This is the only
  316. // condition that returns false.
  317. //
  318. // If the strategy returns with LinearSolverTerminationType::FAILURE, which
  319. // indicates a numerical failure that could be recovered from by retrying (e.g.
  320. // by increasing the strength of the regularization), we set
  321. // iteration_summary_.step_is_valid to false and return true.
  322. //
  323. // In all other cases, we compute the decrease in the trust region
  324. // model problem. In exact arithmetic, this should always be
  325. // positive, but due to numerical problems in the TrustRegionStrategy
  326. // or round off error when computing the decrease it may be
  327. // negative. In which case again, we set
  328. // iteration_summary_.step_is_valid to false.
  329. bool TrustRegionMinimizer::ComputeTrustRegionStep() {
  330. const double strategy_start_time = WallTimeInSeconds();
  331. iteration_summary_.step_is_valid = false;
  332. TrustRegionStrategy::PerSolveOptions per_solve_options;
  333. per_solve_options.eta = options_.eta;
  334. if (find(options_.trust_region_minimizer_iterations_to_dump.begin(),
  335. options_.trust_region_minimizer_iterations_to_dump.end(),
  336. iteration_summary_.iteration) !=
  337. options_.trust_region_minimizer_iterations_to_dump.end()) {
  338. per_solve_options.dump_format_type =
  339. options_.trust_region_problem_dump_format_type;
  340. per_solve_options.dump_filename_base =
  341. JoinPath(options_.trust_region_problem_dump_directory,
  342. StringPrintf("ceres_solver_iteration_%03d",
  343. iteration_summary_.iteration));
  344. }
  345. TrustRegionStrategy::Summary strategy_summary =
  346. strategy_->ComputeStep(per_solve_options,
  347. jacobian_,
  348. residuals_.data(),
  349. trust_region_step_.data());
  350. if (strategy_summary.termination_type ==
  351. LinearSolverTerminationType::FATAL_ERROR) {
  352. solver_summary_->message =
  353. "Linear solver failed due to unrecoverable "
  354. "non-numeric causes. Please see the error log for clues. ";
  355. solver_summary_->termination_type = FAILURE;
  356. return false;
  357. }
  358. iteration_summary_.step_solver_time_in_seconds =
  359. WallTimeInSeconds() - strategy_start_time;
  360. iteration_summary_.linear_solver_iterations = strategy_summary.num_iterations;
  361. if (strategy_summary.termination_type ==
  362. LinearSolverTerminationType::FAILURE) {
  363. return true;
  364. }
  365. // new_model_cost
  366. // = 1/2 [f + J * step]^2
  367. // = 1/2 [ f'f + 2f'J * step + step' * J' * J * step ]
  368. // model_cost_change
  369. // = cost - new_model_cost
  370. // = f'f/2 - 1/2 [ f'f + 2f'J * step + step' * J' * J * step]
  371. // = -f'J * step - step' * J' * J * step / 2
  372. // = -(J * step)'(f + J * step / 2)
  373. ParallelSetZero(options_.context, options_.num_threads, model_residuals_);
  374. jacobian_->RightMultiplyAndAccumulate(trust_region_step_.data(),
  375. model_residuals_.data(),
  376. options_.context,
  377. options_.num_threads);
  378. model_cost_change_ = -Dot(model_residuals_,
  379. residuals_ + model_residuals_ / 2.0,
  380. options_.context,
  381. options_.num_threads);
  382. // TODO(sameeragarwal)
  383. //
  384. // 1. What happens if model_cost_change_ = 0
  385. // 2. What happens if -epsilon <= model_cost_change_ < 0 for some
  386. // small epsilon due to round off error.
  387. iteration_summary_.step_is_valid = (model_cost_change_ > 0.0);
  388. if (iteration_summary_.step_is_valid) {
  389. // Undo the Jacobian column scaling.
  390. ParallelAssign(options_.context,
  391. options_.num_threads,
  392. delta_,
  393. (trust_region_step_.array() * jacobian_scaling_.array()));
  394. num_consecutive_invalid_steps_ = 0;
  395. }
  396. if (is_not_silent_ && !iteration_summary_.step_is_valid) {
  397. VLOG(1) << "Invalid step: current_cost: " << x_cost_
  398. << " absolute model cost change: " << model_cost_change_
  399. << " relative model cost change: "
  400. << (model_cost_change_ / x_cost_);
  401. }
  402. return true;
  403. }
  404. // Invalid steps can happen due to a number of reasons, and we allow a
  405. // limited number of consecutive failures, and return false if this
  406. // limit is exceeded.
  407. bool TrustRegionMinimizer::HandleInvalidStep() {
  408. // TODO(sameeragarwal): Should we be returning FAILURE or
  409. // NO_CONVERGENCE? The solution value is still usable in many cases,
  410. // it is not clear if we should declare the solver a failure
  411. // entirely. For example the case where model_cost_change ~ 0.0, but
  412. // just slightly negative.
  413. if (++num_consecutive_invalid_steps_ >=
  414. options_.max_num_consecutive_invalid_steps) {
  415. solver_summary_->message = StringPrintf(
  416. "Number of consecutive invalid steps more "
  417. "than Solver::Options::max_num_consecutive_invalid_steps: %d",
  418. options_.max_num_consecutive_invalid_steps);
  419. solver_summary_->termination_type = FAILURE;
  420. return false;
  421. }
  422. strategy_->StepIsInvalid();
  423. // We are going to try and reduce the trust region radius and
  424. // solve again. To do this, we are going to treat this iteration
  425. // as an unsuccessful iteration. Since the various callbacks are
  426. // still executed, we are going to fill the iteration summary
  427. // with data that assumes a step of length zero and no progress.
  428. iteration_summary_.cost = x_cost_ + solver_summary_->fixed_cost;
  429. iteration_summary_.cost_change = 0.0;
  430. iteration_summary_.gradient_max_norm =
  431. solver_summary_->iterations.back().gradient_max_norm;
  432. iteration_summary_.gradient_norm =
  433. solver_summary_->iterations.back().gradient_norm;
  434. iteration_summary_.step_norm = 0.0;
  435. iteration_summary_.relative_decrease = 0.0;
  436. iteration_summary_.eta = options_.eta;
  437. return true;
  438. }
  439. // Use the supplied coordinate descent minimizer to perform inner
  440. // iterations and compute the improvement due to it. Returns the cost
  441. // after performing the inner iterations.
  442. //
  443. // The optimization is performed with candidate_x_ as the starting
  444. // point, and if the optimization is successful, candidate_x_ will be
  445. // updated with the optimized parameters.
  446. void TrustRegionMinimizer::DoInnerIterationsIfNeeded() {
  447. inner_iterations_were_useful_ = false;
  448. if (!inner_iterations_are_enabled_ ||
  449. candidate_cost_ >= std::numeric_limits<double>::max()) {
  450. return;
  451. }
  452. double inner_iteration_start_time = WallTimeInSeconds();
  453. ++solver_summary_->num_inner_iteration_steps;
  454. inner_iteration_x_ = candidate_x_;
  455. Solver::Summary inner_iteration_summary;
  456. options_.inner_iteration_minimizer->Minimize(
  457. options_, inner_iteration_x_.data(), &inner_iteration_summary);
  458. double inner_iteration_cost;
  459. if (!evaluator_->Evaluate(inner_iteration_x_.data(),
  460. &inner_iteration_cost,
  461. nullptr,
  462. nullptr,
  463. nullptr)) {
  464. if (is_not_silent_) {
  465. VLOG(2) << "Inner iteration failed.";
  466. }
  467. return;
  468. }
  469. if (is_not_silent_) {
  470. VLOG(2) << "Inner iteration succeeded; Current cost: " << x_cost_
  471. << " Trust region step cost: " << candidate_cost_
  472. << " Inner iteration cost: " << inner_iteration_cost;
  473. }
  474. candidate_x_ = inner_iteration_x_;
  475. // Normally, the quality of a trust region step is measured by
  476. // the ratio
  477. //
  478. // cost_change
  479. // r = -----------------
  480. // model_cost_change
  481. //
  482. // All the change in the nonlinear objective is due to the trust
  483. // region step so this ratio is a good measure of the quality of
  484. // the trust region radius. However, when inner iterations are
  485. // being used, cost_change includes the contribution of the
  486. // inner iterations and its not fair to credit it all to the
  487. // trust region algorithm. So we change the ratio to be
  488. //
  489. // cost_change
  490. // r = ------------------------------------------------
  491. // (model_cost_change + inner_iteration_cost_change)
  492. //
  493. // Practically we do this by increasing model_cost_change by
  494. // inner_iteration_cost_change.
  495. const double inner_iteration_cost_change =
  496. candidate_cost_ - inner_iteration_cost;
  497. model_cost_change_ += inner_iteration_cost_change;
  498. inner_iterations_were_useful_ = inner_iteration_cost < x_cost_;
  499. const double inner_iteration_relative_progress =
  500. 1.0 - inner_iteration_cost / candidate_cost_;
  501. // Disable inner iterations once the relative improvement
  502. // drops below tolerance.
  503. inner_iterations_are_enabled_ =
  504. (inner_iteration_relative_progress > options_.inner_iteration_tolerance);
  505. if (is_not_silent_ && !inner_iterations_are_enabled_) {
  506. VLOG(2) << "Disabling inner iterations. Progress : "
  507. << inner_iteration_relative_progress;
  508. }
  509. candidate_cost_ = inner_iteration_cost;
  510. solver_summary_->inner_iteration_time_in_seconds +=
  511. WallTimeInSeconds() - inner_iteration_start_time;
  512. }
  513. // Perform a projected line search to improve the objective function
  514. // value along delta.
  515. //
  516. // TODO(sameeragarwal): The current implementation does not do
  517. // anything illegal but is incorrect and not terribly effective.
  518. //
  519. // https://github.com/ceres-solver/ceres-solver/issues/187
  520. void TrustRegionMinimizer::DoLineSearch(const Vector& x,
  521. const Vector& gradient,
  522. const double cost,
  523. Vector* delta) {
  524. LineSearchFunction line_search_function(evaluator_);
  525. LineSearch::Options line_search_options;
  526. line_search_options.is_silent = true;
  527. line_search_options.interpolation_type =
  528. options_.line_search_interpolation_type;
  529. line_search_options.min_step_size = options_.min_line_search_step_size;
  530. line_search_options.sufficient_decrease =
  531. options_.line_search_sufficient_function_decrease;
  532. line_search_options.max_step_contraction =
  533. options_.max_line_search_step_contraction;
  534. line_search_options.min_step_contraction =
  535. options_.min_line_search_step_contraction;
  536. line_search_options.max_num_iterations =
  537. options_.max_num_line_search_step_size_iterations;
  538. line_search_options.sufficient_curvature_decrease =
  539. options_.line_search_sufficient_curvature_decrease;
  540. line_search_options.max_step_expansion =
  541. options_.max_line_search_step_expansion;
  542. line_search_options.function = &line_search_function;
  543. std::string message;
  544. std::unique_ptr<LineSearch> line_search(
  545. LineSearch::Create(ceres::ARMIJO, line_search_options, &message));
  546. LineSearch::Summary line_search_summary;
  547. line_search_function.Init(x, *delta);
  548. line_search->Search(1.0, cost, gradient.dot(*delta), &line_search_summary);
  549. solver_summary_->num_line_search_steps += line_search_summary.num_iterations;
  550. solver_summary_->line_search_cost_evaluation_time_in_seconds +=
  551. line_search_summary.cost_evaluation_time_in_seconds;
  552. solver_summary_->line_search_gradient_evaluation_time_in_seconds +=
  553. line_search_summary.gradient_evaluation_time_in_seconds;
  554. solver_summary_->line_search_polynomial_minimization_time_in_seconds +=
  555. line_search_summary.polynomial_minimization_time_in_seconds;
  556. solver_summary_->line_search_total_time_in_seconds +=
  557. line_search_summary.total_time_in_seconds;
  558. if (line_search_summary.success) {
  559. *delta *= line_search_summary.optimal_point.x;
  560. }
  561. }
  562. // Check if the maximum amount of time allowed by the user for the
  563. // solver has been exceeded, and if so return false after updating
  564. // Solver::Summary::message.
  565. bool TrustRegionMinimizer::MaxSolverTimeReached() {
  566. const double total_solver_time =
  567. WallTimeInSeconds() - start_time_in_secs_ +
  568. solver_summary_->preprocessor_time_in_seconds;
  569. if (total_solver_time < options_.max_solver_time_in_seconds) {
  570. return false;
  571. }
  572. solver_summary_->message = StringPrintf(
  573. "Maximum solver time reached. "
  574. "Total solver time: %e >= %e.",
  575. total_solver_time,
  576. options_.max_solver_time_in_seconds);
  577. solver_summary_->termination_type = NO_CONVERGENCE;
  578. if (is_not_silent_) {
  579. VLOG(1) << "Terminating: " << solver_summary_->message;
  580. }
  581. return true;
  582. }
  583. // Check if the maximum number of iterations allowed by the user for
  584. // the solver has been exceeded, and if so return false after updating
  585. // Solver::Summary::message.
  586. bool TrustRegionMinimizer::MaxSolverIterationsReached() {
  587. if (iteration_summary_.iteration < options_.max_num_iterations) {
  588. return false;
  589. }
  590. solver_summary_->message = StringPrintf(
  591. "Maximum number of iterations reached. "
  592. "Number of iterations: %d.",
  593. iteration_summary_.iteration);
  594. solver_summary_->termination_type = NO_CONVERGENCE;
  595. if (is_not_silent_) {
  596. VLOG(1) << "Terminating: " << solver_summary_->message;
  597. }
  598. return true;
  599. }
  600. // Check convergence based on the max norm of the gradient (only for
  601. // iterations where the step was declared successful).
  602. bool TrustRegionMinimizer::GradientToleranceReached() {
  603. if (!iteration_summary_.step_is_successful ||
  604. iteration_summary_.gradient_max_norm > options_.gradient_tolerance) {
  605. return false;
  606. }
  607. solver_summary_->message = StringPrintf(
  608. "Gradient tolerance reached. "
  609. "Gradient max norm: %e <= %e",
  610. iteration_summary_.gradient_max_norm,
  611. options_.gradient_tolerance);
  612. solver_summary_->termination_type = CONVERGENCE;
  613. if (is_not_silent_) {
  614. VLOG(1) << "Terminating: " << solver_summary_->message;
  615. }
  616. return true;
  617. }
  618. // Check convergence based the size of the trust region radius.
  619. bool TrustRegionMinimizer::MinTrustRegionRadiusReached() {
  620. if (iteration_summary_.trust_region_radius >
  621. options_.min_trust_region_radius) {
  622. return false;
  623. }
  624. solver_summary_->message = StringPrintf(
  625. "Minimum trust region radius reached. "
  626. "Trust region radius: %e <= %e",
  627. iteration_summary_.trust_region_radius,
  628. options_.min_trust_region_radius);
  629. solver_summary_->termination_type = CONVERGENCE;
  630. if (is_not_silent_) {
  631. VLOG(1) << "Terminating: " << solver_summary_->message;
  632. }
  633. return true;
  634. }
  635. // Solver::Options::parameter_tolerance based convergence check.
  636. bool TrustRegionMinimizer::ParameterToleranceReached() {
  637. const double x_norm = x_.norm();
  638. // Compute the norm of the step in the ambient space.
  639. iteration_summary_.step_norm = (x_ - candidate_x_).norm();
  640. const double step_size_tolerance =
  641. options_.parameter_tolerance * (x_norm + options_.parameter_tolerance);
  642. if (iteration_summary_.step_norm > step_size_tolerance) {
  643. return false;
  644. }
  645. solver_summary_->message = StringPrintf(
  646. "Parameter tolerance reached. "
  647. "Relative step_norm: %e <= %e.",
  648. (iteration_summary_.step_norm / (x_norm + options_.parameter_tolerance)),
  649. options_.parameter_tolerance);
  650. solver_summary_->termination_type = CONVERGENCE;
  651. if (is_not_silent_) {
  652. VLOG(1) << "Terminating: " << solver_summary_->message;
  653. }
  654. return true;
  655. }
  656. // Solver::Options::function_tolerance based convergence check.
  657. bool TrustRegionMinimizer::FunctionToleranceReached() {
  658. iteration_summary_.cost_change = x_cost_ - candidate_cost_;
  659. const double absolute_function_tolerance =
  660. options_.function_tolerance * x_cost_;
  661. if (fabs(iteration_summary_.cost_change) > absolute_function_tolerance) {
  662. return false;
  663. }
  664. solver_summary_->message = StringPrintf(
  665. "Function tolerance reached. "
  666. "|cost_change|/cost: %e <= %e",
  667. fabs(iteration_summary_.cost_change) / x_cost_,
  668. options_.function_tolerance);
  669. solver_summary_->termination_type = CONVERGENCE;
  670. if (is_not_silent_) {
  671. VLOG(1) << "Terminating: " << solver_summary_->message;
  672. }
  673. return true;
  674. }
  675. // Compute candidate_x_ = Plus(x_, delta_)
  676. // Evaluate the cost of candidate_x_ as candidate_cost_.
  677. //
  678. // Failure to compute the step or the cost mean that candidate_cost_ is set to
  679. // std::numeric_limits<double>::max(). Unlike EvaluateGradientAndJacobian,
  680. // failure in this function is not fatal as we are only computing and evaluating
  681. // a candidate point, and if for some reason we are unable to evaluate it, we
  682. // consider it to be a point with very high cost. This allows the user to deal
  683. // with edge cases/constraints as part of the Manifold and CostFunction objects.
  684. void TrustRegionMinimizer::ComputeCandidatePointAndEvaluateCost() {
  685. if (!evaluator_->Plus(x_.data(), delta_.data(), candidate_x_.data())) {
  686. if (is_not_silent_) {
  687. LOG(WARNING) << "x_plus_delta = Plus(x, delta) failed. "
  688. << "Treating it as a step with infinite cost";
  689. }
  690. candidate_cost_ = std::numeric_limits<double>::max();
  691. return;
  692. }
  693. if (!evaluator_->Evaluate(
  694. candidate_x_.data(), &candidate_cost_, nullptr, nullptr, nullptr)) {
  695. if (is_not_silent_) {
  696. LOG(WARNING) << "Step failed to evaluate. "
  697. << "Treating it as a step with infinite cost";
  698. }
  699. candidate_cost_ = std::numeric_limits<double>::max();
  700. }
  701. }
  702. bool TrustRegionMinimizer::IsStepSuccessful() {
  703. iteration_summary_.relative_decrease =
  704. step_evaluator_->StepQuality(candidate_cost_, model_cost_change_);
  705. // In most cases, boosting the model_cost_change by the
  706. // improvement caused by the inner iterations is fine, but it can
  707. // be the case that the original trust region step was so bad that
  708. // the resulting improvement in the cost was negative, and the
  709. // change caused by the inner iterations was large enough to
  710. // improve the step, but also to make relative decrease quite
  711. // small.
  712. //
  713. // This can cause the trust region loop to reject this step. To
  714. // get around this, we explicitly check if the inner iterations
  715. // led to a net decrease in the objective function value. If
  716. // they did, we accept the step even if the trust region ratio
  717. // is small.
  718. //
  719. // Notice that we do not just check that cost_change is positive
  720. // which is a weaker condition and would render the
  721. // min_relative_decrease threshold useless. Instead, we keep
  722. // track of inner_iterations_were_useful, which is true only
  723. // when inner iterations lead to a net decrease in the cost.
  724. return (inner_iterations_were_useful_ ||
  725. iteration_summary_.relative_decrease >
  726. options_.min_relative_decrease);
  727. }
  728. // Declare the step successful, move to candidate_x, update the
  729. // derivatives and let the trust region strategy and the step
  730. // evaluator know that the step has been accepted.
  731. bool TrustRegionMinimizer::HandleSuccessfulStep() {
  732. x_ = candidate_x_;
  733. // Since the step was successful, this point has already had the residual
  734. // evaluated (but not the jacobian). So indicate that to the evaluator.
  735. if (!EvaluateGradientAndJacobian(/*new_evaluation_point=*/false)) {
  736. return false;
  737. }
  738. iteration_summary_.step_is_successful = true;
  739. strategy_->StepAccepted(iteration_summary_.relative_decrease);
  740. step_evaluator_->StepAccepted(candidate_cost_, model_cost_change_);
  741. return true;
  742. }
  743. } // namespace ceres::internal