Forward relative_step_size to Ridders in gradient checker GradientChecker uses DynamicNumericDiffCostFunction<CostFunction, RIDDERS>, which reads NumericDiffOptions::ridders_relative_initial_step_size rather than NumericDiffOptions::relative_step_size. Update CreateGradientCheckingCostFunction to set ridders_relative_initial_step_size, reuse it in CreateGradientCheckingProblemImpl, and change the default of Solver::Options::gradient_check_numeric_derivative_relative_step_size from 1e-6 to 1e-2 to match Ridders' default. Thanks to @reprojection-calibration and @NatMatLogica for reporting and analyzing this. Fixes https://github.com/ceres-solver/ceres-solver/issues/1206 Change-Id: I37c16a60ef4c608663d4b93a77183ad9a5d063c2
diff --git a/docs/source/nnls_solving.rst b/docs/source/nnls_solving.rst index e24b92d..3054f5a 100644 --- a/docs/source/nnls_solving.rst +++ b/docs/source/nnls_solving.rst
@@ -2042,36 +2042,26 @@ .. member:: double Solver::Options::gradient_check_numeric_derivative_relative_step_size - Default: ``1e-6`` + Default: ``1e-2`` .. NOTE:: This option only applies to the numeric differentiation used for - checking the user provided derivatives when when + checking the user provided derivatives when `Solver::Options::check_gradients` is true. If you are using :class:`NumericDiffCostFunction` and are interested in changing the step size for numeric differentiation in your cost function, please have a look at :class:`NumericDiffOptions`. - Relative shift used for taking numeric derivatives when - `Solver::Options::check_gradients` is `true`. + Relative initial step size used for taking numeric derivatives (via + Ridders' adaptive extrapolation method; see + :member:`NumericDiffOptions::ridders_relative_initial_step_size`) + when `Solver::Options::check_gradients` is `true`. - For finite differencing, each dimension is evaluated at slightly - shifted values, e.g., for forward differences, the numerical - derivative is - - .. math:: - - \delta &= gradient\_check\_numeric\_derivative\_relative\_step\_size\\ - \Delta f &= \frac{f((1 + \delta) x) - f(x)}{\delta x} - - The finite differencing is done along each dimension. The reason to - use a relative (rather than absolute) step size is that this way, - numeric differentiation works for functions where the arguments are - typically large (e.g. :math:`10^9`) and when the values are small - (e.g. :math:`10^{-5}`). It is possible to construct *torture cases* - which break this finite difference heuristic, but they do not come - up often in practice. + If parameters are close to zero, Ridders' method sets the initial + step size directly to this value; otherwise it is multiplied by the + parameter's magnitude. As the derivative is estimated across + Romberg extrapolations, the step size decreases. .. member:: bool Solver::Options::update_state_every_iteration
diff --git a/include/ceres/solver.h b/include/ceres/solver.h index baa6fa6..4c7e146 100644 --- a/include/ceres/solver.h +++ b/include/ceres/solver.h
@@ -756,31 +756,17 @@ // function, please have a look at // include/ceres/numeric_diff_options.h. // - // Relative shift used for taking numeric derivatives when + // Relative initial step size used for taking numeric derivatives + // (via Ridders' adaptive extrapolation method; see + // NumericDiffOptions::ridders_relative_initial_step_size) when // Solver::Options::check_gradients is true. // - // For finite differencing, each dimension is evaluated at - // slightly shifted values; for the case of central difference, - // this is what gets evaluated: - // - // delta = gradient_check_numeric_derivative_relative_step_size; - // f_initial = f(x) - // f_forward = f((1 + delta) * x) - // f_backward = f((1 - delta) * x) - // - // The finite differencing is done along each dimension. The - // reason to use a relative (rather than absolute) step size is - // that this way, numeric differentiation works for functions where - // the arguments are typically large (e.g. 1e9) and when the - // values are small (e.g. 1e-5). It is possible to construct - // "torture cases" which break this finite difference heuristic, - // but they do not come up often in practice. - // - // TODO(keir): Pick a smarter number than the default above! In - // theory a good choice is sqrt(eps) * x, which for doubles means - // about 1e-8 * x. However, I have found this number too - // optimistic. This number should be exposed for users to change. - double gradient_check_numeric_derivative_relative_step_size = 1e-6; + // If parameters are close to zero, Ridders' method sets the + // initial step size directly to this value; otherwise it is + // multiplied by the parameter's magnitude. As the derivative is + // estimated across Romberg extrapolations, the step size + // decreases. + double gradient_check_numeric_derivative_relative_step_size = 1e-2; // If update_state_every_iteration is true, then Ceres Solver will // guarantee that at the end of every iteration and before any
diff --git a/internal/ceres/gradient_checking_cost_function.cc b/internal/ceres/gradient_checking_cost_function.cc index 228c42c..2752511 100644 --- a/internal/ceres/gradient_checking_cost_function.cc +++ b/internal/ceres/gradient_checking_cost_function.cc
@@ -160,7 +160,7 @@ const std::string& extra_info, GradientCheckingIterationCallback* callback) { NumericDiffOptions numeric_diff_options; - numeric_diff_options.relative_step_size = relative_step_size; + numeric_diff_options.ridders_relative_initial_step_size = relative_step_size; return std::make_unique<GradientCheckingCostFunction>(cost_function, manifolds, @@ -188,9 +188,6 @@ gradient_checking_problem_options.manifold_ownership = DO_NOT_TAKE_OWNERSHIP; gradient_checking_problem_options.context = problem_impl->context(); - NumericDiffOptions numeric_diff_options; - numeric_diff_options.relative_step_size = relative_step_size; - auto gradient_checking_problem_impl = std::make_unique<ProblemImpl>(gradient_checking_problem_options); @@ -253,20 +250,18 @@ } // Wrap the original CostFunction in a GradientCheckingCostFunction. - CostFunction* gradient_checking_cost_function = - new GradientCheckingCostFunction(residual_block->cost_function(), - &manifolds, - numeric_diff_options, - relative_precision, - extra_info, - callback); - // The const_cast is necessary because // ProblemImpl::AddResidualBlock can potentially take ownership of // the LossFunction, but in this case we are guaranteed that this // will not be the case, so this const_cast is harmless. gradient_checking_problem_impl->AddResidualBlock( - gradient_checking_cost_function, + CreateGradientCheckingCostFunction(residual_block->cost_function(), + &manifolds, + relative_step_size, + relative_precision, + extra_info, + callback) + .release(), const_cast<LossFunction*>(residual_block->loss_function()), parameter_blocks.data(), static_cast<int>(parameter_blocks.size()));
diff --git a/internal/ceres/gradient_checking_cost_function_test.cc b/internal/ceres/gradient_checking_cost_function_test.cc index 7dd334e..c7ccb73 100644 --- a/internal/ceres/gradient_checking_cost_function_test.cc +++ b/internal/ceres/gradient_checking_cost_function_test.cc
@@ -449,4 +449,47 @@ } } +TEST(GradientCheckingCostFunction, RelativeStepSizeIsRespected) { + struct HighFrequencyCostFunction : SizedCostFunction<1, 1> { + bool Evaluate(double const* const* parameters, + double* residuals, + double** jacobians) const override { + const double x = parameters[0][0]; + residuals[0] = std::sin(1000.0 * x); + if (jacobians != nullptr && jacobians[0] != nullptr) { + jacobians[0][0] = 1000.0 * std::cos(1000.0 * x); + } + return true; + } + }; + + HighFrequencyCostFunction cost_function; + double x = 1.0; + double residual = 0.0; + double jacobian = 0.0; + double* parameters[] = {&x}; + double* jacobians[] = {&jacobian}; + + // At the default step size (1e-2), 1000 * x shifts by 10 radians (> 2*pi), + // so Ridders' extrapolation aliases across periods and rejects the exact + // analytic derivative. + { + GradientCheckingIterationCallback callback; + auto checker = CreateGradientCheckingCostFunction( + &cost_function, nullptr, 1e-2, 1e-6, "", &callback); + EXPECT_TRUE(checker->Evaluate(parameters, &residual, jacobians)); + EXPECT_TRUE(callback.gradient_error_detected()); + } + + // With a smaller relative_step_size (1e-5), Ridders' extrapolation resolves + // the derivative and the check passes. + { + GradientCheckingIterationCallback callback; + auto checker = CreateGradientCheckingCostFunction( + &cost_function, nullptr, 1e-5, 1e-6, "", &callback); + EXPECT_TRUE(checker->Evaluate(parameters, &residual, jacobians)); + EXPECT_FALSE(callback.gradient_error_detected()); + } +} + } // namespace ceres::internal