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