gradient_checking_cost_function_test.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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/gradient_checking_cost_function.h"
  31. #include <cmath>
  32. #include <cstdint>
  33. #include <memory>
  34. #include <random>
  35. #include <vector>
  36. #include "ceres/cost_function.h"
  37. #include "ceres/loss_function.h"
  38. #include "ceres/manifold.h"
  39. #include "ceres/parameter_block.h"
  40. #include "ceres/problem_impl.h"
  41. #include "ceres/program.h"
  42. #include "ceres/residual_block.h"
  43. #include "ceres/sized_cost_function.h"
  44. #include "ceres/types.h"
  45. #include "glog/logging.h"
  46. #include "gmock/gmock.h"
  47. #include "gtest/gtest.h"
  48. namespace ceres::internal {
  49. using testing::_;
  50. using testing::AllOf;
  51. using testing::AnyNumber;
  52. using testing::HasSubstr;
  53. // Pick a (non-quadratic) function whose derivative are easy:
  54. //
  55. // f = exp(- a' x).
  56. // df = - f a.
  57. //
  58. // where 'a' is a vector of the same size as 'x'. In the block
  59. // version, they are both block vectors, of course.
  60. template <int bad_block = 1, int bad_variable = 2>
  61. class TestTerm : public CostFunction {
  62. public:
  63. // The constructor of this function needs to know the number
  64. // of blocks desired, and the size of each block.
  65. template <class UniformRandomFunctor>
  66. TestTerm(int arity, int const* dim, UniformRandomFunctor&& randu)
  67. : arity_(arity) {
  68. // Make 'arity' random vectors.
  69. a_.resize(arity_);
  70. for (int j = 0; j < arity_; ++j) {
  71. a_[j].resize(dim[j]);
  72. for (int u = 0; u < dim[j]; ++u) {
  73. a_[j][u] = randu();
  74. }
  75. }
  76. for (int i = 0; i < arity_; i++) {
  77. mutable_parameter_block_sizes()->push_back(dim[i]);
  78. }
  79. set_num_residuals(1);
  80. }
  81. bool Evaluate(double const* const* parameters,
  82. double* residuals,
  83. double** jacobians) const override {
  84. // Compute a . x.
  85. double ax = 0;
  86. for (int j = 0; j < arity_; ++j) {
  87. for (int u = 0; u < parameter_block_sizes()[j]; ++u) {
  88. ax += a_[j][u] * parameters[j][u];
  89. }
  90. }
  91. // This is the cost, but also appears as a factor
  92. // in the derivatives.
  93. double f = *residuals = exp(-ax);
  94. // Accumulate 1st order derivatives.
  95. if (jacobians) {
  96. for (int j = 0; j < arity_; ++j) {
  97. if (jacobians[j]) {
  98. for (int u = 0; u < parameter_block_sizes()[j]; ++u) {
  99. // See comments before class.
  100. jacobians[j][u] = -f * a_[j][u];
  101. if (bad_block == j && bad_variable == u) {
  102. // Whoopsiedoopsie! Deliberately introduce a faulty jacobian entry
  103. // like what happens when users make an error in their jacobian
  104. // computations. This should get detected.
  105. LOG(INFO) << "Poisoning jacobian for parameter block " << j
  106. << ", row 0, column " << u;
  107. jacobians[j][u] += 500;
  108. }
  109. }
  110. }
  111. }
  112. }
  113. return true;
  114. }
  115. private:
  116. int arity_;
  117. std::vector<std::vector<double>> a_;
  118. };
  119. TEST(GradientCheckingCostFunction, ResidualsAndJacobiansArePreservedTest) {
  120. // Test with 3 blocks of size 2, 3 and 4.
  121. int const arity = 3;
  122. int const dim[arity] = {2, 3, 4};
  123. // Make a random set of blocks.
  124. std::vector<double*> parameters(arity);
  125. std::mt19937 prng;
  126. std::uniform_real_distribution<double> distribution(-1.0, 1.0);
  127. auto randu = [&prng, &distribution] { return distribution(prng); };
  128. for (int j = 0; j < arity; ++j) {
  129. parameters[j] = new double[dim[j]];
  130. for (int u = 0; u < dim[j]; ++u) {
  131. parameters[j][u] = randu();
  132. }
  133. }
  134. double original_residual;
  135. double residual;
  136. std::vector<double*> original_jacobians(arity);
  137. std::vector<double*> jacobians(arity);
  138. for (int j = 0; j < arity; ++j) {
  139. // Since residual is one dimensional the jacobians have the same
  140. // size as the parameter blocks.
  141. jacobians[j] = new double[dim[j]];
  142. original_jacobians[j] = new double[dim[j]];
  143. }
  144. const double kRelativeStepSize = 1e-6;
  145. const double kRelativePrecision = 1e-4;
  146. TestTerm<-1, -1> term(arity, dim, randu);
  147. GradientCheckingIterationCallback callback;
  148. auto gradient_checking_cost_function =
  149. CreateGradientCheckingCostFunction(&term,
  150. nullptr,
  151. kRelativeStepSize,
  152. kRelativePrecision,
  153. "Ignored.",
  154. &callback);
  155. term.Evaluate(&parameters[0], &original_residual, &original_jacobians[0]);
  156. gradient_checking_cost_function->Evaluate(
  157. &parameters[0], &residual, &jacobians[0]);
  158. EXPECT_EQ(original_residual, residual);
  159. for (int j = 0; j < arity; j++) {
  160. for (int k = 0; k < dim[j]; ++k) {
  161. EXPECT_EQ(original_jacobians[j][k], jacobians[j][k]);
  162. }
  163. delete[] parameters[j];
  164. delete[] jacobians[j];
  165. delete[] original_jacobians[j];
  166. }
  167. }
  168. TEST(GradientCheckingCostFunction, SmokeTest) {
  169. // Test with 3 blocks of size 2, 3 and 4.
  170. int const arity = 3;
  171. int const dim[arity] = {2, 3, 4};
  172. // Make a random set of blocks.
  173. std::vector<double*> parameters(arity);
  174. std::mt19937 prng;
  175. std::uniform_real_distribution<double> distribution(-1.0, 1.0);
  176. auto randu = [&prng, &distribution] { return distribution(prng); };
  177. for (int j = 0; j < arity; ++j) {
  178. parameters[j] = new double[dim[j]];
  179. for (int u = 0; u < dim[j]; ++u) {
  180. parameters[j][u] = randu();
  181. }
  182. }
  183. double residual;
  184. std::vector<double*> jacobians(arity);
  185. for (int j = 0; j < arity; ++j) {
  186. // Since residual is one dimensional the jacobians have the same size as the
  187. // parameter blocks.
  188. jacobians[j] = new double[dim[j]];
  189. }
  190. const double kRelativeStepSize = 1e-6;
  191. const double kRelativePrecision = 1e-4;
  192. // Should have one term that's bad, causing everything to get dumped.
  193. LOG(INFO) << "Bad gradient";
  194. {
  195. TestTerm<1, 2> term(arity, dim, randu);
  196. GradientCheckingIterationCallback callback;
  197. auto gradient_checking_cost_function =
  198. CreateGradientCheckingCostFunction(&term,
  199. nullptr,
  200. kRelativeStepSize,
  201. kRelativePrecision,
  202. "Fuzzy banana",
  203. &callback);
  204. EXPECT_TRUE(gradient_checking_cost_function->Evaluate(
  205. &parameters[0], &residual, &jacobians[0]));
  206. EXPECT_TRUE(callback.gradient_error_detected());
  207. EXPECT_TRUE(callback.error_log().find("Fuzzy banana") != std::string::npos);
  208. EXPECT_TRUE(callback.error_log().find(
  209. "(1,0,2) Relative error worse than") != std::string::npos);
  210. }
  211. // The gradient is correct, so no errors are reported.
  212. LOG(INFO) << "Good gradient";
  213. {
  214. TestTerm<-1, -1> term(arity, dim, randu);
  215. GradientCheckingIterationCallback callback;
  216. auto gradient_checking_cost_function =
  217. CreateGradientCheckingCostFunction(&term,
  218. nullptr,
  219. kRelativeStepSize,
  220. kRelativePrecision,
  221. "Fuzzy banana",
  222. &callback);
  223. EXPECT_TRUE(gradient_checking_cost_function->Evaluate(
  224. &parameters[0], &residual, &jacobians[0]));
  225. EXPECT_FALSE(callback.gradient_error_detected());
  226. }
  227. for (int j = 0; j < arity; j++) {
  228. delete[] parameters[j];
  229. delete[] jacobians[j];
  230. }
  231. }
  232. // The following three classes are for the purposes of defining
  233. // function signatures. They have dummy Evaluate functions.
  234. // Trivial cost function that accepts a single argument.
  235. class UnaryCostFunction : public CostFunction {
  236. public:
  237. UnaryCostFunction(int num_residuals, int32_t parameter_block_size) {
  238. set_num_residuals(num_residuals);
  239. mutable_parameter_block_sizes()->push_back(parameter_block_size);
  240. }
  241. bool Evaluate(double const* const* parameters,
  242. double* residuals,
  243. double** jacobians) const final {
  244. for (int i = 0; i < num_residuals(); ++i) {
  245. residuals[i] = 1;
  246. }
  247. return true;
  248. }
  249. };
  250. // Trivial cost function that accepts two arguments.
  251. class BinaryCostFunction : public CostFunction {
  252. public:
  253. BinaryCostFunction(int num_residuals,
  254. int32_t parameter_block1_size,
  255. int32_t parameter_block2_size) {
  256. set_num_residuals(num_residuals);
  257. mutable_parameter_block_sizes()->push_back(parameter_block1_size);
  258. mutable_parameter_block_sizes()->push_back(parameter_block2_size);
  259. }
  260. bool Evaluate(double const* const* parameters,
  261. double* residuals,
  262. double** jacobians) const final {
  263. for (int i = 0; i < num_residuals(); ++i) {
  264. residuals[i] = 2;
  265. }
  266. return true;
  267. }
  268. };
  269. // Trivial cost function that accepts three arguments.
  270. class TernaryCostFunction : public CostFunction {
  271. public:
  272. TernaryCostFunction(int num_residuals,
  273. int32_t parameter_block1_size,
  274. int32_t parameter_block2_size,
  275. int32_t parameter_block3_size) {
  276. set_num_residuals(num_residuals);
  277. mutable_parameter_block_sizes()->push_back(parameter_block1_size);
  278. mutable_parameter_block_sizes()->push_back(parameter_block2_size);
  279. mutable_parameter_block_sizes()->push_back(parameter_block3_size);
  280. }
  281. bool Evaluate(double const* const* parameters,
  282. double* residuals,
  283. double** jacobians) const final {
  284. for (int i = 0; i < num_residuals(); ++i) {
  285. residuals[i] = 3;
  286. }
  287. return true;
  288. }
  289. };
  290. // Verify that the two ParameterBlocks are formed from the same user
  291. // array and have the same Manifold objects.
  292. static void ParameterBlocksAreEquivalent(const ParameterBlock* left,
  293. const ParameterBlock* right) {
  294. CHECK(left != nullptr);
  295. CHECK(right != nullptr);
  296. EXPECT_EQ(left->user_state(), right->user_state());
  297. EXPECT_EQ(left->Size(), right->Size());
  298. EXPECT_EQ(left->Size(), right->Size());
  299. EXPECT_EQ(left->TangentSize(), right->TangentSize());
  300. EXPECT_EQ(left->manifold(), right->manifold());
  301. EXPECT_EQ(left->IsConstant(), right->IsConstant());
  302. }
  303. TEST(GradientCheckingProblemImpl, ProblemDimensionsMatch) {
  304. // Parameter blocks with arbitrarily chosen initial values.
  305. double x[] = {1.0, 2.0, 3.0};
  306. double y[] = {4.0, 5.0, 6.0, 7.0};
  307. double z[] = {8.0, 9.0, 10.0, 11.0, 12.0};
  308. double w[] = {13.0, 14.0, 15.0, 16.0};
  309. ProblemImpl problem_impl;
  310. problem_impl.AddParameterBlock(x, 3);
  311. problem_impl.AddParameterBlock(y, 4);
  312. problem_impl.SetParameterBlockConstant(y);
  313. problem_impl.AddParameterBlock(z, 5);
  314. problem_impl.AddParameterBlock(w, 4, new QuaternionManifold);
  315. // clang-format off
  316. problem_impl.AddResidualBlock(new UnaryCostFunction(2, 3),
  317. nullptr, x);
  318. problem_impl.AddResidualBlock(new BinaryCostFunction(6, 5, 4),
  319. nullptr, z, y);
  320. problem_impl.AddResidualBlock(new BinaryCostFunction(3, 3, 5),
  321. new TrivialLoss, x, z);
  322. problem_impl.AddResidualBlock(new BinaryCostFunction(7, 5, 3),
  323. nullptr, z, x);
  324. problem_impl.AddResidualBlock(new TernaryCostFunction(1, 5, 3, 4),
  325. nullptr, z, x, y);
  326. // clang-format on
  327. GradientCheckingIterationCallback callback;
  328. auto gradient_checking_problem_impl =
  329. CreateGradientCheckingProblemImpl(&problem_impl, 1.0, 1.0, &callback);
  330. // The dimensions of the two problems match.
  331. EXPECT_EQ(problem_impl.NumParameterBlocks(),
  332. gradient_checking_problem_impl->NumParameterBlocks());
  333. EXPECT_EQ(problem_impl.NumResidualBlocks(),
  334. gradient_checking_problem_impl->NumResidualBlocks());
  335. EXPECT_EQ(problem_impl.NumParameters(),
  336. gradient_checking_problem_impl->NumParameters());
  337. EXPECT_EQ(problem_impl.NumResiduals(),
  338. gradient_checking_problem_impl->NumResiduals());
  339. const Program& program = problem_impl.program();
  340. const Program& gradient_checking_program =
  341. gradient_checking_problem_impl->program();
  342. // Since we added the ParameterBlocks and ResidualBlocks explicitly,
  343. // they should be in the same order in the two programs. It is
  344. // possible that may change due to implementation changes to
  345. // Program. This is not expected to be the case and writing code to
  346. // anticipate that possibility not worth the extra complexity in
  347. // this test.
  348. for (int i = 0; i < program.parameter_blocks().size(); ++i) {
  349. ParameterBlocksAreEquivalent(
  350. program.parameter_blocks()[i],
  351. gradient_checking_program.parameter_blocks()[i]);
  352. }
  353. for (int i = 0; i < program.residual_blocks().size(); ++i) {
  354. // Compare the sizes of the two ResidualBlocks.
  355. const ResidualBlock* original_residual_block = program.residual_blocks()[i];
  356. const ResidualBlock* new_residual_block =
  357. gradient_checking_program.residual_blocks()[i];
  358. EXPECT_EQ(original_residual_block->NumParameterBlocks(),
  359. new_residual_block->NumParameterBlocks());
  360. EXPECT_EQ(original_residual_block->NumResiduals(),
  361. new_residual_block->NumResiduals());
  362. EXPECT_EQ(original_residual_block->NumScratchDoublesForEvaluate(),
  363. new_residual_block->NumScratchDoublesForEvaluate());
  364. // Verify that the ParameterBlocks for the two residuals are equivalent.
  365. for (int j = 0; j < original_residual_block->NumParameterBlocks(); ++j) {
  366. ParameterBlocksAreEquivalent(
  367. original_residual_block->parameter_blocks()[j],
  368. new_residual_block->parameter_blocks()[j]);
  369. }
  370. }
  371. }
  372. TEST(GradientCheckingProblemImpl, ConstrainedProblemBoundsArePropagated) {
  373. // Parameter blocks with arbitrarily chosen initial values.
  374. double x[] = {1.0, 2.0, 3.0};
  375. ProblemImpl problem_impl;
  376. problem_impl.AddParameterBlock(x, 3);
  377. problem_impl.AddResidualBlock(new UnaryCostFunction(2, 3), nullptr, x);
  378. problem_impl.SetParameterLowerBound(x, 0, 0.9);
  379. problem_impl.SetParameterUpperBound(x, 1, 2.5);
  380. GradientCheckingIterationCallback callback;
  381. auto gradient_checking_problem_impl =
  382. CreateGradientCheckingProblemImpl(&problem_impl, 1.0, 1.0, &callback);
  383. // The dimensions of the two problems match.
  384. EXPECT_EQ(problem_impl.NumParameterBlocks(),
  385. gradient_checking_problem_impl->NumParameterBlocks());
  386. EXPECT_EQ(problem_impl.NumResidualBlocks(),
  387. gradient_checking_problem_impl->NumResidualBlocks());
  388. EXPECT_EQ(problem_impl.NumParameters(),
  389. gradient_checking_problem_impl->NumParameters());
  390. EXPECT_EQ(problem_impl.NumResiduals(),
  391. gradient_checking_problem_impl->NumResiduals());
  392. for (int i = 0; i < 3; ++i) {
  393. EXPECT_EQ(problem_impl.GetParameterLowerBound(x, i),
  394. gradient_checking_problem_impl->GetParameterLowerBound(x, i));
  395. EXPECT_EQ(problem_impl.GetParameterUpperBound(x, i),
  396. gradient_checking_problem_impl->GetParameterUpperBound(x, i));
  397. }
  398. }
  399. } // namespace ceres::internal