program_evaluator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2023 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: keir@google.com (Keir Mierle)
  30. //
  31. // The ProgramEvaluator runs the cost functions contained in each residual block
  32. // and stores the result into a jacobian. The particular type of jacobian is
  33. // abstracted out using two template parameters:
  34. //
  35. // - An "EvaluatePreparer" that is responsible for creating the array with
  36. // pointers to the jacobian blocks where the cost function evaluates to.
  37. // - A "JacobianWriter" that is responsible for storing the resulting
  38. // jacobian blocks in the passed sparse matrix.
  39. //
  40. // This abstraction affords an efficient evaluator implementation while still
  41. // supporting writing to multiple sparse matrix formats. For example, when the
  42. // ProgramEvaluator is parameterized for writing to block sparse matrices, the
  43. // residual jacobians are written directly into their final position in the
  44. // block sparse matrix by the user's CostFunction; there is no copying.
  45. //
  46. // The evaluation is threaded with C++ threads.
  47. //
  48. // The EvaluatePreparer and JacobianWriter interfaces are as follows:
  49. //
  50. // class EvaluatePreparer {
  51. // // Prepare the jacobians array for use as the destination of a call to
  52. // // a cost function's evaluate method.
  53. // void Prepare(const ResidualBlock* residual_block,
  54. // int residual_block_index,
  55. // SparseMatrix* jacobian,
  56. // double** jacobians);
  57. // }
  58. //
  59. // class JacobianWriter {
  60. // // Create a jacobian that this writer can write. Same as
  61. // // Evaluator::CreateJacobian.
  62. // std::unique_ptr<SparseMatrix> CreateJacobian() const;
  63. //
  64. // // Create num_threads evaluate preparers.Resulting preparers are valid
  65. // // while *this is.
  66. //
  67. // std::unique_ptr<EvaluatePreparer[]> CreateEvaluatePreparers(
  68. // int num_threads);
  69. //
  70. // // Write the block jacobians from a residual block evaluation to the
  71. // // larger sparse jacobian.
  72. // void Write(int residual_id,
  73. // int residual_offset,
  74. // double** jacobians,
  75. // SparseMatrix* jacobian);
  76. // }
  77. //
  78. // Note: The ProgramEvaluator is not thread safe, since internally it maintains
  79. // some per-thread scratch space.
  80. #ifndef CERES_INTERNAL_PROGRAM_EVALUATOR_H_
  81. #define CERES_INTERNAL_PROGRAM_EVALUATOR_H_
  82. // This include must come before any #ifndef check on Ceres compile options.
  83. // clang-format off
  84. #include "ceres/internal/config.h"
  85. // clang-format on
  86. #include <atomic>
  87. #include <map>
  88. #include <memory>
  89. #include <string>
  90. #include <vector>
  91. #include "ceres/evaluation_callback.h"
  92. #include "ceres/execution_summary.h"
  93. #include "ceres/internal/eigen.h"
  94. #include "ceres/parallel_for.h"
  95. #include "ceres/parallel_vector_ops.h"
  96. #include "ceres/parameter_block.h"
  97. #include "ceres/program.h"
  98. #include "ceres/residual_block.h"
  99. #include "ceres/small_blas.h"
  100. namespace ceres {
  101. namespace internal {
  102. struct NullJacobianFinalizer {
  103. void operator()(SparseMatrix* /*jacobian*/, int /*num_parameters*/) {}
  104. };
  105. template <typename EvaluatePreparer,
  106. typename JacobianWriter,
  107. typename JacobianFinalizer = NullJacobianFinalizer>
  108. class ProgramEvaluator final : public Evaluator {
  109. public:
  110. ProgramEvaluator(const Evaluator::Options& options, Program* program)
  111. : options_(options),
  112. program_(program),
  113. jacobian_writer_(options, program),
  114. evaluate_preparers_(std::move(
  115. jacobian_writer_.CreateEvaluatePreparers(options.num_threads))),
  116. num_parameters_(program->NumEffectiveParameters()) {
  117. BuildResidualLayout(*program, &residual_layout_);
  118. evaluate_scratch_ = std::move(CreateEvaluatorScratch(
  119. *program, static_cast<unsigned>(options.num_threads)));
  120. }
  121. // Implementation of Evaluator interface.
  122. std::unique_ptr<SparseMatrix> CreateJacobian() const final {
  123. return jacobian_writer_.CreateJacobian();
  124. }
  125. bool Evaluate(const Evaluator::EvaluateOptions& evaluate_options,
  126. const double* state,
  127. double* cost,
  128. double* residuals,
  129. double* gradient,
  130. SparseMatrix* jacobian) final {
  131. ScopedExecutionTimer total_timer("Evaluator::Total", &execution_summary_);
  132. ScopedExecutionTimer call_type_timer(
  133. gradient == nullptr && jacobian == nullptr ? "Evaluator::Residual"
  134. : "Evaluator::Jacobian",
  135. &execution_summary_);
  136. // The parameters are stateful, so set the state before evaluating.
  137. if (!program_->StateVectorToParameterBlocks(state)) {
  138. return false;
  139. }
  140. // Notify the user about a new evaluation point if they are interested.
  141. if (options_.evaluation_callback != nullptr) {
  142. program_->CopyParameterBlockStateToUserState();
  143. options_.evaluation_callback->PrepareForEvaluation(
  144. /*jacobians=*/(gradient != nullptr || jacobian != nullptr),
  145. evaluate_options.new_evaluation_point);
  146. }
  147. if (residuals != nullptr) {
  148. ParallelSetZero(options_.context,
  149. options_.num_threads,
  150. residuals,
  151. program_->NumResiduals());
  152. }
  153. if (jacobian != nullptr) {
  154. jacobian->SetZero(options_.context, options_.num_threads);
  155. }
  156. // Each thread gets it's own cost and evaluate scratch space.
  157. for (int i = 0; i < options_.num_threads; ++i) {
  158. evaluate_scratch_[i].cost = 0.0;
  159. if (gradient != nullptr) {
  160. ParallelSetZero(options_.context,
  161. options_.num_threads,
  162. evaluate_scratch_[i].gradient.get(),
  163. num_parameters_);
  164. }
  165. }
  166. const int num_residual_blocks = program_->NumResidualBlocks();
  167. // This bool is used to disable the loop if an error is encountered without
  168. // breaking out of it. The remaining loop iterations are still run, but with
  169. // an empty body, and so will finish quickly.
  170. std::atomic_bool abort(false);
  171. ParallelFor(
  172. options_.context,
  173. 0,
  174. num_residual_blocks,
  175. options_.num_threads,
  176. [&](int thread_id, int i) {
  177. if (abort) {
  178. return;
  179. }
  180. EvaluatePreparer* preparer = &evaluate_preparers_[thread_id];
  181. EvaluateScratch* scratch = &evaluate_scratch_[thread_id];
  182. // Prepare block residuals if requested.
  183. const ResidualBlock* residual_block = program_->residual_blocks()[i];
  184. double* block_residuals = nullptr;
  185. if (residuals != nullptr) {
  186. block_residuals = residuals + residual_layout_[i];
  187. } else if (gradient != nullptr) {
  188. block_residuals = scratch->residual_block_residuals.get();
  189. }
  190. // Prepare block jacobians if requested.
  191. double** block_jacobians = nullptr;
  192. if (jacobian != nullptr || gradient != nullptr) {
  193. preparer->Prepare(residual_block,
  194. i,
  195. jacobian,
  196. scratch->jacobian_block_ptrs.get());
  197. block_jacobians = scratch->jacobian_block_ptrs.get();
  198. }
  199. // Evaluate the cost, residuals, and jacobians.
  200. double block_cost;
  201. if (!residual_block->Evaluate(
  202. evaluate_options.apply_loss_function,
  203. &block_cost,
  204. block_residuals,
  205. block_jacobians,
  206. scratch->residual_block_evaluate_scratch.get())) {
  207. abort = true;
  208. return;
  209. }
  210. scratch->cost += block_cost;
  211. // Store the jacobians, if they were requested.
  212. if (jacobian != nullptr) {
  213. jacobian_writer_.Write(
  214. i, residual_layout_[i], block_jacobians, jacobian);
  215. }
  216. // Compute and store the gradient, if it was requested.
  217. if (gradient != nullptr) {
  218. int num_residuals = residual_block->NumResiduals();
  219. int num_parameter_blocks = residual_block->NumParameterBlocks();
  220. for (int j = 0; j < num_parameter_blocks; ++j) {
  221. const ParameterBlock* parameter_block =
  222. residual_block->parameter_blocks()[j];
  223. if (parameter_block->IsConstant()) {
  224. continue;
  225. }
  226. MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
  227. block_jacobians[j],
  228. num_residuals,
  229. parameter_block->TangentSize(),
  230. block_residuals,
  231. scratch->gradient.get() + parameter_block->delta_offset());
  232. }
  233. }
  234. });
  235. if (abort) {
  236. return false;
  237. }
  238. // Sum the cost and gradient (if requested) from each thread.
  239. (*cost) = 0.0;
  240. if (gradient != nullptr) {
  241. auto gradient_vector = VectorRef(gradient, num_parameters_);
  242. ParallelSetZero(options_.context, options_.num_threads, gradient_vector);
  243. }
  244. for (int i = 0; i < options_.num_threads; ++i) {
  245. (*cost) += evaluate_scratch_[i].cost;
  246. if (gradient != nullptr) {
  247. auto gradient_vector = VectorRef(gradient, num_parameters_);
  248. ParallelAssign(
  249. options_.context,
  250. options_.num_threads,
  251. gradient_vector,
  252. gradient_vector + VectorRef(evaluate_scratch_[i].gradient.get(),
  253. num_parameters_));
  254. }
  255. }
  256. // It is possible that after accumulation that the cost has become infinite
  257. // or a nan.
  258. if (!std::isfinite(*cost)) {
  259. LOG(ERROR) << "Accumulated cost = " << *cost
  260. << " is not a finite number. Evaluation failed.";
  261. return false;
  262. }
  263. // Finalize the Jacobian if it is available.
  264. // `num_parameters` is passed to the finalizer so that additional
  265. // storage can be reserved for additional diagonal elements if
  266. // necessary.
  267. if (jacobian != nullptr) {
  268. JacobianFinalizer f;
  269. f(jacobian, num_parameters_);
  270. }
  271. return true;
  272. }
  273. bool Plus(const double* state,
  274. const double* delta,
  275. double* state_plus_delta) const final {
  276. return program_->Plus(
  277. state, delta, state_plus_delta, options_.context, options_.num_threads);
  278. }
  279. int NumParameters() const final { return program_->NumParameters(); }
  280. int NumEffectiveParameters() const final {
  281. return program_->NumEffectiveParameters();
  282. }
  283. int NumResiduals() const final { return program_->NumResiduals(); }
  284. std::map<std::string, CallStatistics> Statistics() const final {
  285. return execution_summary_.statistics();
  286. }
  287. private:
  288. // Per-thread scratch space needed to evaluate and store each residual block.
  289. struct EvaluateScratch {
  290. void Init(int max_parameters_per_residual_block,
  291. int max_scratch_doubles_needed_for_evaluate,
  292. int max_residuals_per_residual_block,
  293. int num_parameters) {
  294. residual_block_evaluate_scratch =
  295. std::make_unique<double[]>(max_scratch_doubles_needed_for_evaluate);
  296. gradient = std::make_unique<double[]>(num_parameters);
  297. VectorRef(gradient.get(), num_parameters).setZero();
  298. residual_block_residuals =
  299. std::make_unique<double[]>(max_residuals_per_residual_block);
  300. jacobian_block_ptrs =
  301. std::make_unique<double*[]>(max_parameters_per_residual_block);
  302. }
  303. double cost;
  304. std::unique_ptr<double[]> residual_block_evaluate_scratch;
  305. // The gradient on the manifold.
  306. std::unique_ptr<double[]> gradient;
  307. // Enough space to store the residual for the largest residual block.
  308. std::unique_ptr<double[]> residual_block_residuals;
  309. std::unique_ptr<double*[]> jacobian_block_ptrs;
  310. };
  311. static void BuildResidualLayout(const Program& program,
  312. std::vector<int>* residual_layout) {
  313. const std::vector<ResidualBlock*>& residual_blocks =
  314. program.residual_blocks();
  315. residual_layout->resize(program.NumResidualBlocks());
  316. int residual_pos = 0;
  317. for (int i = 0; i < residual_blocks.size(); ++i) {
  318. const int num_residuals = residual_blocks[i]->NumResiduals();
  319. (*residual_layout)[i] = residual_pos;
  320. residual_pos += num_residuals;
  321. }
  322. }
  323. // Create scratch space for each thread evaluating the program.
  324. static std::unique_ptr<EvaluateScratch[]> CreateEvaluatorScratch(
  325. const Program& program, unsigned num_threads) {
  326. int max_parameters_per_residual_block =
  327. program.MaxParametersPerResidualBlock();
  328. int max_scratch_doubles_needed_for_evaluate =
  329. program.MaxScratchDoublesNeededForEvaluate();
  330. int max_residuals_per_residual_block =
  331. program.MaxResidualsPerResidualBlock();
  332. int num_parameters = program.NumEffectiveParameters();
  333. auto evaluate_scratch = std::make_unique<EvaluateScratch[]>(num_threads);
  334. for (int i = 0; i < num_threads; i++) {
  335. evaluate_scratch[i].Init(max_parameters_per_residual_block,
  336. max_scratch_doubles_needed_for_evaluate,
  337. max_residuals_per_residual_block,
  338. num_parameters);
  339. }
  340. return evaluate_scratch;
  341. }
  342. Evaluator::Options options_;
  343. Program* program_;
  344. JacobianWriter jacobian_writer_;
  345. std::unique_ptr<EvaluatePreparer[]> evaluate_preparers_;
  346. std::unique_ptr<EvaluateScratch[]> evaluate_scratch_;
  347. std::vector<int> residual_layout_;
  348. int num_parameters_;
  349. ::ceres::internal::ExecutionSummary execution_summary_;
  350. };
  351. } // namespace internal
  352. } // namespace ceres
  353. #endif // CERES_INTERNAL_PROGRAM_EVALUATOR_H_