|
1 | 1 | use super::simd; |
2 | 2 | use super::{ |
3 | 3 | CurveProblem, CurveProblemPredictionLoss, DEFAULT_SPLINE_KNOTS, FitError, |
4 | | - IncrementalSplineFitRunner, IncrementalSplineFitStep, MetricQuantization, |
5 | | - MetricQuantizationDecimalPlaces, OptimizationLossMetric, SplineConfig, SplineDuplicateXPolicy, |
6 | | - SplineExtrapolation, SplineFamilyKind, SplineFinalizeContext, SplineKnotStrategy, |
7 | | - approximate_spline_knots, build_spline_initial_curve_from_knot_y, |
8 | | - build_spline_result_from_knot_y, calculate_iteration_metrics, |
9 | | - calculate_iteration_metrics_with_quantization, calculate_metrics, evaluate_linear_spline, |
10 | | - expanded_spline_curve_x_bounds, fit_akima_spline, fit_akima_spline_with_config, fit_curve, |
11 | | - fit_curve_with_optimizer_config, fit_curve_with_progress, |
12 | | - fit_curve_with_progress_and_optimizer_config, |
| 4 | + HESSIAN_DIAGONAL_JITTER, HESSIAN_FD_MIN_STEP, HESSIAN_FD_REL_STEP, IncrementalSplineFitRunner, |
| 5 | + IncrementalSplineFitStep, MetricQuantization, MetricQuantizationDecimalPlaces, |
| 6 | + OptimizationLossMetric, SplineConfig, SplineDuplicateXPolicy, SplineExtrapolation, |
| 7 | + SplineFamilyKind, SplineFinalizeContext, SplineKnotStrategy, approximate_spline_knots, |
| 8 | + build_spline_initial_curve_from_knot_y, build_spline_result_from_knot_y, |
| 9 | + calculate_iteration_metrics, calculate_iteration_metrics_with_quantization, calculate_metrics, |
| 10 | + evaluate_linear_spline, expanded_spline_curve_x_bounds, fit_akima_spline, |
| 11 | + fit_akima_spline_with_config, fit_curve, fit_curve_with_optimizer_config, |
| 12 | + fit_curve_with_progress, fit_curve_with_progress_and_optimizer_config, |
13 | 13 | fit_curve_with_progress_and_optimizer_config_and_loss_metric, fit_linear_spline, |
14 | 14 | fit_linear_spline_with_config, fit_monotone_cubic_spline, fit_natural_cubic_spline, |
15 | | - sorted_points_with_duplicate_policy, |
| 15 | + numerical_hessian_from_gradient, sorted_points_with_duplicate_policy, |
16 | 16 | }; |
17 | 17 | use crate::domain::{ |
18 | 18 | AdamConfig, CurveFamily, CurveParams, InputError, LbfgsConfig, NelderMeadConfig, |
19 | 19 | NewtonCgConfig, OptimizerConfig, Point, Points, SgdConfig, SteepestDescentConfig, |
20 | 20 | }; |
21 | 21 | use crate::models::{self, ObjectiveGrad, ObjectiveHessian, ObjectiveValue, PredictionLoss}; |
| 22 | +use argmin::core::Gradient; |
| 23 | +use ndarray::Array1; |
22 | 24 |
|
23 | 25 | #[derive(Clone, Copy)] |
24 | 26 | struct MsePredictionLoss; |
@@ -65,6 +67,115 @@ fn quantization(decimal_places: u8) -> MetricQuantization { |
65 | 67 | ) |
66 | 68 | } |
67 | 69 |
|
| 70 | +struct RetryGradientProblem { |
| 71 | + center: f64, |
| 72 | + invalid_step: f64, |
| 73 | +} |
| 74 | + |
| 75 | +struct AlwaysInvalidGradientProblem; |
| 76 | + |
| 77 | +impl Gradient for RetryGradientProblem { |
| 78 | + type Param = Array1<f64>; |
| 79 | + type Gradient = Array1<f64>; |
| 80 | + |
| 81 | + fn gradient(&self, param: &Self::Param) -> Result<Self::Gradient, argmin::core::Error> { |
| 82 | + let delta = (param[0] - self.center).abs(); |
| 83 | + if (delta - self.invalid_step).abs() <= 1e-14 { |
| 84 | + return Ok(Array1::from_vec(vec![f64::NAN])); |
| 85 | + } |
| 86 | + Ok(Array1::from_vec(vec![2.0 * param[0]])) |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +impl Gradient for AlwaysInvalidGradientProblem { |
| 91 | + type Param = Array1<f64>; |
| 92 | + type Gradient = Array1<f64>; |
| 93 | + |
| 94 | + fn gradient(&self, param: &Self::Param) -> Result<Self::Gradient, argmin::core::Error> { |
| 95 | + Ok(Array1::from_vec(vec![f64::NAN; param.len()])) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[test] |
| 100 | +fn central_diff_gradient_retries_step_when_primary_step_is_invalid() { |
| 101 | + let param = [1.0_f64]; |
| 102 | + let rel_step = 1e-3; |
| 103 | + let min_step = 1e-3; |
| 104 | + let base_step = ((param[0].abs() + 1.0) * rel_step).max(min_step); |
| 105 | + let mut gradient = [0.0]; |
| 106 | + models::central_diff_gradient_from_value( |
| 107 | + ¶m, |
| 108 | + rel_step, |
| 109 | + min_step, |
| 110 | + |probe| { |
| 111 | + let delta = (probe[0] - param[0]).abs(); |
| 112 | + if (delta - base_step).abs() <= 1e-14 { |
| 113 | + f64::NAN |
| 114 | + } else { |
| 115 | + probe[0] * probe[0] |
| 116 | + } |
| 117 | + }, |
| 118 | + &mut gradient, |
| 119 | + ); |
| 120 | + |
| 121 | + assert_near(gradient[0], 2.0, 1e-10); |
| 122 | +} |
| 123 | + |
| 124 | +#[test] |
| 125 | +fn central_diff_hessian_retries_step_when_primary_step_is_invalid() { |
| 126 | + let param = [1.0_f64]; |
| 127 | + let rel_step = 1e-3; |
| 128 | + let min_step = 1e-3; |
| 129 | + let base_step = ((param[0].abs() + 1.0) * rel_step).max(min_step); |
| 130 | + let hessian = models::central_diff_hessian_from_gradient( |
| 131 | + ¶m, |
| 132 | + rel_step, |
| 133 | + min_step, |
| 134 | + |probe, gradient_out| { |
| 135 | + let delta = (probe[0] - param[0]).abs(); |
| 136 | + gradient_out[0] = if (delta - base_step).abs() <= 1e-14 { |
| 137 | + f64::NAN |
| 138 | + } else { |
| 139 | + 2.0 * probe[0] |
| 140 | + }; |
| 141 | + }, |
| 142 | + ); |
| 143 | + |
| 144 | + assert_near(hessian[[0, 0]], 2.0, 1e-10); |
| 145 | +} |
| 146 | + |
| 147 | +#[test] |
| 148 | +fn fit_numerical_hessian_retries_step_when_primary_step_is_invalid() { |
| 149 | + let param = Array1::from_vec(vec![1.0_f64]); |
| 150 | + let base_step = ((param[0].abs() + 1.0) * HESSIAN_FD_REL_STEP).max(HESSIAN_FD_MIN_STEP); |
| 151 | + let problem = RetryGradientProblem { |
| 152 | + center: param[0], |
| 153 | + invalid_step: base_step, |
| 154 | + }; |
| 155 | + let hessian = |
| 156 | + numerical_hessian_from_gradient(&problem, ¶m).expect("hessian must be computed"); |
| 157 | + |
| 158 | + assert_near(hessian[[0, 0]], 2.0 + HESSIAN_DIAGONAL_JITTER, 1e-10); |
| 159 | +} |
| 160 | + |
| 161 | +#[test] |
| 162 | +fn central_diff_gradient_falls_back_to_zero_when_all_retry_steps_invalid() { |
| 163 | + let param = [1.0_f64]; |
| 164 | + let mut gradient = [123.0]; |
| 165 | + models::central_diff_gradient_from_value(¶m, 1e-3, 1e-3, |_probe| f64::NAN, &mut gradient); |
| 166 | + |
| 167 | + assert_eq!(gradient[0], 0.0); |
| 168 | +} |
| 169 | + |
| 170 | +#[test] |
| 171 | +fn fit_numerical_hessian_falls_back_to_diagonal_jitter_when_all_retry_steps_invalid() { |
| 172 | + let param = Array1::from_vec(vec![1.0_f64]); |
| 173 | + let hessian = numerical_hessian_from_gradient(&AlwaysInvalidGradientProblem, ¶m) |
| 174 | + .expect("hessian must be computed even with invalid gradients"); |
| 175 | + |
| 176 | + assert_near(hessian[[0, 0]], HESSIAN_DIAGONAL_JITTER, 1e-15); |
| 177 | +} |
| 178 | + |
68 | 179 | #[test] |
69 | 180 | fn curve_objective_arrhenius_is_consistent_across_levels() { |
70 | 181 | let x_values = [0.4, 0.8, 1.4, 2.5, 4.0]; |
|
0 commit comments