block_jacobian_writer.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. #include "ceres/block_jacobian_writer.h"
  31. #include <algorithm>
  32. #include <memory>
  33. #include <vector>
  34. #include "ceres/block_evaluate_preparer.h"
  35. #include "ceres/block_sparse_matrix.h"
  36. #include "ceres/internal/eigen.h"
  37. #include "ceres/internal/export.h"
  38. #include "ceres/parameter_block.h"
  39. #include "ceres/program.h"
  40. #include "ceres/residual_block.h"
  41. namespace ceres::internal {
  42. namespace {
  43. // Given the residual block ordering, build a lookup table to determine which
  44. // per-parameter jacobian goes where in the overall program jacobian.
  45. //
  46. // Since we expect to use a Schur type linear solver to solve the LM step, take
  47. // extra care to place the E blocks and the F blocks contiguously. E blocks are
  48. // the first num_eliminate_blocks parameter blocks as indicated by the parameter
  49. // block ordering. The remaining parameter blocks are the F blocks.
  50. //
  51. // In order to simplify handling block-sparse to CRS conversion, cells within
  52. // the row-block of non-partitioned matrix are stored in memory sequentially in
  53. // the order of increasing column-block id. In case of partitioned matrices,
  54. // cells corresponding to F sub-matrix are stored sequentially in the order of
  55. // increasing column-block id (with cells corresponding to E sub-matrix stored
  56. // separately).
  57. //
  58. // TODO(keir): Consider if we should use a boolean for each parameter block
  59. // instead of num_eliminate_blocks.
  60. bool BuildJacobianLayout(const Program& program,
  61. int num_eliminate_blocks,
  62. std::vector<int*>* jacobian_layout,
  63. std::vector<int>* jacobian_layout_storage) {
  64. const std::vector<ResidualBlock*>& residual_blocks =
  65. program.residual_blocks();
  66. // Iterate over all the active residual blocks and determine how many E blocks
  67. // are there. This will determine where the F blocks start in the jacobian
  68. // matrix. Also compute the number of jacobian blocks.
  69. unsigned int f_block_pos = 0;
  70. unsigned int num_jacobian_blocks = 0;
  71. for (auto* residual_block : residual_blocks) {
  72. const int num_residuals = residual_block->NumResiduals();
  73. const int num_parameter_blocks = residual_block->NumParameterBlocks();
  74. // Advance f_block_pos over each E block for this residual.
  75. for (int j = 0; j < num_parameter_blocks; ++j) {
  76. ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
  77. if (!parameter_block->IsConstant()) {
  78. // Only count blocks for active parameters.
  79. num_jacobian_blocks++;
  80. if (parameter_block->index() < num_eliminate_blocks) {
  81. f_block_pos += num_residuals * parameter_block->TangentSize();
  82. }
  83. }
  84. }
  85. if (num_jacobian_blocks > std::numeric_limits<int>::max()) {
  86. LOG(ERROR) << "Overlow error. Too many blocks in the jacobian matrix : "
  87. << num_jacobian_blocks;
  88. return false;
  89. }
  90. }
  91. // We now know that the E blocks are laid out starting at zero, and the F
  92. // blocks are laid out starting at f_block_pos. Iterate over the residual
  93. // blocks again, and this time fill the jacobian_layout array with the
  94. // position information.
  95. jacobian_layout->resize(program.NumResidualBlocks());
  96. jacobian_layout_storage->resize(num_jacobian_blocks);
  97. int e_block_pos = 0;
  98. int* jacobian_pos = jacobian_layout_storage->data();
  99. std::vector<std::pair<int, int>> active_parameter_blocks;
  100. for (int i = 0; i < residual_blocks.size(); ++i) {
  101. const ResidualBlock* residual_block = residual_blocks[i];
  102. const int num_residuals = residual_block->NumResiduals();
  103. const int num_parameter_blocks = residual_block->NumParameterBlocks();
  104. (*jacobian_layout)[i] = jacobian_pos;
  105. // Cells from F sub-matrix are to be stored sequentially with increasing
  106. // column block id. For each non-constant parameter block, a pair of indices
  107. // (index in the list of active parameter blocks and index in the list of
  108. // all parameter blocks) is computed, and index pairs are sorted by the
  109. // index of corresponding column block id.
  110. active_parameter_blocks.clear();
  111. active_parameter_blocks.reserve(num_parameter_blocks);
  112. for (int j = 0; j < num_parameter_blocks; ++j) {
  113. ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
  114. if (parameter_block->IsConstant()) {
  115. continue;
  116. }
  117. const int k = active_parameter_blocks.size();
  118. active_parameter_blocks.emplace_back(k, j);
  119. }
  120. std::sort(active_parameter_blocks.begin(),
  121. active_parameter_blocks.end(),
  122. [&residual_block](const std::pair<int, int>& a,
  123. const std::pair<int, int>& b) {
  124. return residual_block->parameter_blocks()[a.second]->index() <
  125. residual_block->parameter_blocks()[b.second]->index();
  126. });
  127. // Cell positions for each active parameter block are filled in the order of
  128. // active parameter block indices sorted by columnd block index. This
  129. // guarantees that cells are laid out sequentially with increasing column
  130. // block indices.
  131. for (const auto& indices : active_parameter_blocks) {
  132. const auto [k, j] = indices;
  133. ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
  134. const int parameter_block_index = parameter_block->index();
  135. const int jacobian_block_size =
  136. num_residuals * parameter_block->TangentSize();
  137. if (parameter_block_index < num_eliminate_blocks) {
  138. jacobian_pos[k] = e_block_pos;
  139. e_block_pos += jacobian_block_size;
  140. } else {
  141. jacobian_pos[k] = static_cast<int>(f_block_pos);
  142. f_block_pos += jacobian_block_size;
  143. if (f_block_pos > std::numeric_limits<int>::max()) {
  144. LOG(ERROR)
  145. << "Overlow error. Too many entries in the Jacobian matrix.";
  146. return false;
  147. }
  148. }
  149. }
  150. jacobian_pos += active_parameter_blocks.size();
  151. }
  152. return true;
  153. }
  154. } // namespace
  155. BlockJacobianWriter::BlockJacobianWriter(const Evaluator::Options& options,
  156. Program* program)
  157. : options_(options), program_(program) {
  158. CHECK_GE(options.num_eliminate_blocks, 0)
  159. << "num_eliminate_blocks must be greater than 0.";
  160. jacobian_layout_is_valid_ = BuildJacobianLayout(*program,
  161. options.num_eliminate_blocks,
  162. &jacobian_layout_,
  163. &jacobian_layout_storage_);
  164. }
  165. // Create evaluate preparers that point directly into the final jacobian. This
  166. // makes the final Write() a nop.
  167. std::unique_ptr<BlockEvaluatePreparer[]>
  168. BlockJacobianWriter::CreateEvaluatePreparers(unsigned num_threads) {
  169. const int max_derivatives_per_residual_block =
  170. program_->MaxDerivativesPerResidualBlock();
  171. auto preparers = std::make_unique<BlockEvaluatePreparer[]>(num_threads);
  172. for (unsigned i = 0; i < num_threads; i++) {
  173. preparers[i].Init(jacobian_layout_.data(),
  174. max_derivatives_per_residual_block);
  175. }
  176. return preparers;
  177. }
  178. std::unique_ptr<SparseMatrix> BlockJacobianWriter::CreateJacobian() const {
  179. if (!jacobian_layout_is_valid_) {
  180. LOG(ERROR) << "Unable to create Jacobian matrix. Too many entries in the "
  181. "Jacobian matrix.";
  182. return nullptr;
  183. }
  184. auto* bs = new CompressedRowBlockStructure;
  185. const std::vector<ParameterBlock*>& parameter_blocks =
  186. program_->parameter_blocks();
  187. // Construct the column blocks.
  188. bs->cols.resize(parameter_blocks.size());
  189. for (int i = 0, cursor = 0; i < parameter_blocks.size(); ++i) {
  190. CHECK_NE(parameter_blocks[i]->index(), -1);
  191. CHECK(!parameter_blocks[i]->IsConstant());
  192. bs->cols[i].size = parameter_blocks[i]->TangentSize();
  193. bs->cols[i].position = cursor;
  194. cursor += bs->cols[i].size;
  195. }
  196. // Construct the cells in each row.
  197. const std::vector<ResidualBlock*>& residual_blocks =
  198. program_->residual_blocks();
  199. int row_block_position = 0;
  200. bs->rows.resize(residual_blocks.size());
  201. for (int i = 0; i < residual_blocks.size(); ++i) {
  202. const ResidualBlock* residual_block = residual_blocks[i];
  203. CompressedRow* row = &bs->rows[i];
  204. row->block.size = residual_block->NumResiduals();
  205. row->block.position = row_block_position;
  206. row_block_position += row->block.size;
  207. // Size the row by the number of active parameters in this residual.
  208. const int num_parameter_blocks = residual_block->NumParameterBlocks();
  209. int num_active_parameter_blocks = 0;
  210. for (int j = 0; j < num_parameter_blocks; ++j) {
  211. if (residual_block->parameter_blocks()[j]->index() != -1) {
  212. num_active_parameter_blocks++;
  213. }
  214. }
  215. row->cells.resize(num_active_parameter_blocks);
  216. // Add layout information for the active parameters in this row.
  217. for (int j = 0, k = 0; j < num_parameter_blocks; ++j) {
  218. const ParameterBlock* parameter_block =
  219. residual_block->parameter_blocks()[j];
  220. if (!parameter_block->IsConstant()) {
  221. Cell& cell = row->cells[k];
  222. cell.block_id = parameter_block->index();
  223. cell.position = jacobian_layout_[i][k];
  224. // Only increment k for active parameters, since there is only layout
  225. // information for active parameters.
  226. k++;
  227. }
  228. }
  229. std::sort(row->cells.begin(), row->cells.end(), CellLessThan);
  230. }
  231. return std::make_unique<BlockSparseMatrix>(
  232. bs, options_.sparse_linear_algebra_library_type == CUDA_SPARSE);
  233. }
  234. } // namespace ceres::internal