dynamic_autodiff_cost_function.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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: sameeragarwal@google.com (Sameer Agarwal)
  30. // mierle@gmail.com (Keir Mierle)
  31. #ifndef CERES_PUBLIC_DYNAMIC_AUTODIFF_COST_FUNCTION_H_
  32. #define CERES_PUBLIC_DYNAMIC_AUTODIFF_COST_FUNCTION_H_
  33. #include <cmath>
  34. #include <memory>
  35. #include <numeric>
  36. #include <vector>
  37. #include "ceres/dynamic_cost_function.h"
  38. #include "ceres/internal/fixed_array.h"
  39. #include "ceres/jet.h"
  40. #include "ceres/types.h"
  41. #include "glog/logging.h"
  42. namespace ceres {
  43. // This autodiff implementation differs from the one found in
  44. // autodiff_cost_function.h by supporting autodiff on cost functions
  45. // with variable numbers of parameters with variable sizes. With the
  46. // other implementation, all the sizes (both the number of parameter
  47. // blocks and the size of each block) must be fixed at compile time.
  48. //
  49. // The functor API differs slightly from the API for fixed size
  50. // autodiff; the expected interface for the cost functors is:
  51. //
  52. // struct MyCostFunctor {
  53. // template<typename T>
  54. // bool operator()(T const* const* parameters, T* residuals) const {
  55. // // Use parameters[i] to access the i'th parameter block.
  56. // }
  57. // };
  58. //
  59. // Since the sizing of the parameters is done at runtime, you must
  60. // also specify the sizes after creating the dynamic autodiff cost
  61. // function. For example:
  62. //
  63. // DynamicAutoDiffCostFunction<MyCostFunctor, 3> cost_function(
  64. // new MyCostFunctor());
  65. // cost_function.AddParameterBlock(5);
  66. // cost_function.AddParameterBlock(10);
  67. // cost_function.SetNumResiduals(21);
  68. //
  69. // Under the hood, the implementation evaluates the cost function
  70. // multiple times, computing a small set of the derivatives (four by
  71. // default, controlled by the Stride template parameter) with each
  72. // pass. There is a tradeoff with the size of the passes; you may want
  73. // to experiment with the stride.
  74. template <typename CostFunctor, int Stride = 4>
  75. class DynamicAutoDiffCostFunction final : public DynamicCostFunction {
  76. public:
  77. // Takes ownership by default.
  78. explicit DynamicAutoDiffCostFunction(CostFunctor* functor,
  79. Ownership ownership = TAKE_OWNERSHIP)
  80. : functor_(functor), ownership_(ownership) {}
  81. DynamicAutoDiffCostFunction(DynamicAutoDiffCostFunction&& other)
  82. : functor_(std::move(other.functor_)), ownership_(other.ownership_) {}
  83. ~DynamicAutoDiffCostFunction() override {
  84. // Manually release pointer if configured to not take ownership
  85. // rather than deleting only if ownership is taken. This is to
  86. // stay maximally compatible to old user code which may have
  87. // forgotten to implement a virtual destructor, from when the
  88. // AutoDiffCostFunction always took ownership.
  89. if (ownership_ == DO_NOT_TAKE_OWNERSHIP) {
  90. functor_.release();
  91. }
  92. }
  93. bool Evaluate(double const* const* parameters,
  94. double* residuals,
  95. double** jacobians) const override {
  96. CHECK_GT(num_residuals(), 0)
  97. << "You must call DynamicAutoDiffCostFunction::SetNumResiduals() "
  98. << "before DynamicAutoDiffCostFunction::Evaluate().";
  99. if (jacobians == nullptr) {
  100. return (*functor_)(parameters, residuals);
  101. }
  102. // The difficulty with Jets, as implemented in Ceres, is that they were
  103. // originally designed for strictly compile-sized use. At this point, there
  104. // is a large body of code that assumes inside a cost functor it is
  105. // acceptable to do e.g. T(1.5) and get an appropriately sized jet back.
  106. //
  107. // Unfortunately, it is impossible to communicate the expected size of a
  108. // dynamically sized jet to the static instantiations that existing code
  109. // depends on.
  110. //
  111. // To work around this issue, the solution here is to evaluate the
  112. // jacobians in a series of passes, each one computing Stride *
  113. // num_residuals() derivatives. This is done with small, fixed-size jets.
  114. const int num_parameter_blocks =
  115. static_cast<int>(parameter_block_sizes().size());
  116. const int num_parameters = std::accumulate(
  117. parameter_block_sizes().begin(), parameter_block_sizes().end(), 0);
  118. // Allocate scratch space for the strided evaluation.
  119. using JetT = Jet<double, Stride>;
  120. internal::FixedArray<JetT, (256 * 7) / sizeof(JetT)> input_jets(
  121. num_parameters);
  122. internal::FixedArray<JetT, (256 * 7) / sizeof(JetT)> output_jets(
  123. num_residuals());
  124. // Make the parameter pack that is sent to the functor (reused).
  125. internal::FixedArray<Jet<double, Stride>*> jet_parameters(
  126. num_parameter_blocks, nullptr);
  127. int num_active_parameters = 0;
  128. // To handle constant parameters between non-constant parameter blocks, the
  129. // start position --- a raw parameter index --- of each contiguous block of
  130. // non-constant parameters is recorded in start_derivative_section.
  131. std::vector<int> start_derivative_section;
  132. bool in_derivative_section = false;
  133. int parameter_cursor = 0;
  134. // Discover the derivative sections and set the parameter values.
  135. for (int i = 0; i < num_parameter_blocks; ++i) {
  136. jet_parameters[i] = &input_jets[parameter_cursor];
  137. const int parameter_block_size = parameter_block_sizes()[i];
  138. if (jacobians[i] != nullptr) {
  139. if (!in_derivative_section) {
  140. start_derivative_section.push_back(parameter_cursor);
  141. in_derivative_section = true;
  142. }
  143. num_active_parameters += parameter_block_size;
  144. } else {
  145. in_derivative_section = false;
  146. }
  147. for (int j = 0; j < parameter_block_size; ++j, parameter_cursor++) {
  148. input_jets[parameter_cursor].a = parameters[i][j];
  149. }
  150. }
  151. if (num_active_parameters == 0) {
  152. return (*functor_)(parameters, residuals);
  153. }
  154. // When `num_active_parameters % Stride != 0` then it can be the case
  155. // that `active_parameter_count < Stride` while parameter_cursor is less
  156. // than the total number of parameters and with no remaining non-constant
  157. // parameter blocks. Pushing parameter_cursor (the total number of
  158. // parameters) as a final entry to start_derivative_section is required
  159. // because if a constant parameter block is encountered after the
  160. // last non-constant block then current_derivative_section is incremented
  161. // and would otherwise index an invalid position in
  162. // start_derivative_section. Setting the final element to the total number
  163. // of parameters means that this can only happen at most once in the loop
  164. // below.
  165. start_derivative_section.push_back(parameter_cursor);
  166. // Evaluate all of the strides. Each stride is a chunk of the derivative to
  167. // evaluate, typically some size proportional to the size of the SIMD
  168. // registers of the CPU.
  169. int num_strides = static_cast<int>(
  170. ceil(num_active_parameters / static_cast<float>(Stride)));
  171. int current_derivative_section = 0;
  172. int current_derivative_section_cursor = 0;
  173. for (int pass = 0; pass < num_strides; ++pass) {
  174. // Set most of the jet components to zero, except for
  175. // non-constant #Stride parameters.
  176. const int initial_derivative_section = current_derivative_section;
  177. const int initial_derivative_section_cursor =
  178. current_derivative_section_cursor;
  179. int active_parameter_count = 0;
  180. parameter_cursor = 0;
  181. for (int i = 0; i < num_parameter_blocks; ++i) {
  182. for (int j = 0; j < parameter_block_sizes()[i];
  183. ++j, parameter_cursor++) {
  184. input_jets[parameter_cursor].v.setZero();
  185. if (active_parameter_count < Stride &&
  186. parameter_cursor >=
  187. (start_derivative_section[current_derivative_section] +
  188. current_derivative_section_cursor)) {
  189. if (jacobians[i] != nullptr) {
  190. input_jets[parameter_cursor].v[active_parameter_count] = 1.0;
  191. ++active_parameter_count;
  192. ++current_derivative_section_cursor;
  193. } else {
  194. ++current_derivative_section;
  195. current_derivative_section_cursor = 0;
  196. }
  197. }
  198. }
  199. }
  200. if (!(*functor_)(&jet_parameters[0], &output_jets[0])) {
  201. return false;
  202. }
  203. // Copy the pieces of the jacobians into their final place.
  204. active_parameter_count = 0;
  205. current_derivative_section = initial_derivative_section;
  206. current_derivative_section_cursor = initial_derivative_section_cursor;
  207. for (int i = 0, parameter_cursor = 0; i < num_parameter_blocks; ++i) {
  208. for (int j = 0; j < parameter_block_sizes()[i];
  209. ++j, parameter_cursor++) {
  210. if (active_parameter_count < Stride &&
  211. parameter_cursor >=
  212. (start_derivative_section[current_derivative_section] +
  213. current_derivative_section_cursor)) {
  214. if (jacobians[i] != nullptr) {
  215. for (int k = 0; k < num_residuals(); ++k) {
  216. jacobians[i][k * parameter_block_sizes()[i] + j] =
  217. output_jets[k].v[active_parameter_count];
  218. }
  219. ++active_parameter_count;
  220. ++current_derivative_section_cursor;
  221. } else {
  222. ++current_derivative_section;
  223. current_derivative_section_cursor = 0;
  224. }
  225. }
  226. }
  227. }
  228. // Only copy the residuals over once (even though we compute them on
  229. // every loop).
  230. if (pass == num_strides - 1) {
  231. for (int k = 0; k < num_residuals(); ++k) {
  232. residuals[k] = output_jets[k].a;
  233. }
  234. }
  235. }
  236. return true;
  237. }
  238. private:
  239. std::unique_ptr<CostFunctor> functor_;
  240. Ownership ownership_;
  241. };
  242. // Deduction guide that allows the user to avoid explicitly specifying the
  243. // template parameter of DynamicAutoDiffCostFunction. The class can instead be
  244. // instantiated as follows:
  245. //
  246. // new DynamicAutoDiffCostFunction{new MyCostFunctor{}};
  247. //
  248. template <typename CostFunctor>
  249. DynamicAutoDiffCostFunction(CostFunctor* functor, Ownership ownership)
  250. -> DynamicAutoDiffCostFunction<CostFunctor>;
  251. } // namespace ceres
  252. #endif // CERES_PUBLIC_DYNAMIC_AUTODIFF_COST_FUNCTION_H_