Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Example: Fitting a spring-mass model to data

In this example we'll fit a damped spring-mass system to some synthetic data (using the model to generate the data). The system consists of a mass \(m\) attached to a spring with spring constant \(k\), and a damping force proportional to the velocity of the mass with damping coefficient \(c\).

\[ \begin{align*} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= -\frac{k}{m} x - \frac{c}{m} v \end{align*} \]

where \(v = \frac{dx}{dt}\) is the velocity of the mass.

We'll use the argmin crate to perform the optimisation. To hold the synthetic data and the model, we'll create a struct Problem like so

use argmin::{
    core::{CostFunction, Executor, Gradient, State},
    solver::{linesearch::MoreThuenteLineSearch, quasinewton::LBFGS},
};
use diffsol::{
    AdjointOdeSolverMethod, DenseMatrix, DiffSl, Matrix, MatrixCommon, NalgebraMat, NalgebraVec,
    OdeBuilder, OdeEquations, OdeSolverMethod, OdeSolverProblem, OdeSolverState, Op, Scale,
    StepVjp, Vector, VectorView, VectorViewMut,
};
use std::cell::RefCell;
use std::time::{Duration, Instant};

type M = NalgebraMat<f64>;
type V = NalgebraVec<f64>;
type T = f64;
type LS = diffsol::NalgebraLU<f64>;
type CG = diffsol::LlvmModule;
type Eqn = DiffSl<M, CG>;

#[derive(Clone, Copy, Debug)]
enum GradientMethod {
    ContinuousAdjoint,
    DiscreteAdjoint,
}

struct Problem {
    ys_data: M,
    ts_data: Vec<T>,
    problem: RefCell<OdeSolverProblem<Eqn>>,
    method: GradientMethod,
}

To use argmin we need to specify traits giving the loss function and its gradient. In this case we'll define a loss function equal to the sum of squares error between the model output and the synthetic data.

$$ \text{loss} = \sum_i (y_i(p) - \hat{y}_i)^2 $$

where \(y_i(p)\) is the model output as a function of the parameters \(p\), and \(\hat{y}_i\) is the observed data at time index \(i\).

impl CostFunction for Problem {
    type Output = T;
    type Param = Vec<T>;

    fn cost(&self, param: &Self::Param) -> Result<Self::Output, argmin_math::Error> {
        let mut problem = self.problem.borrow_mut();
        let context = *problem.eqn().context();
        problem
            .eqn_mut()
            .set_params(&V::from_vec(param.clone(), context));
        let mut solver = problem.bdf::<LS>().unwrap();
        let ys = match solver.solve_dense(&self.ts_data) {
            Ok((ys, _stop_reason)) => ys,
            Err(_) => return Ok(f64::MAX / 1000.),
        };
        let loss = ys
            .inner()
            .column_iter()
            .zip(self.ys_data.inner().column_iter())
            .map(|(a, b)| (a - b).norm_squared())
            .sum::<f64>();
        Ok(loss)
    }
}

The gradient of this cost function with respect to the model outputs \(y_i\) is

$$ \frac{\partial \text{loss}}{\partial y_i} = 2 (y_i(p) - \hat{y}_i) $$

Diffsol gives two methods to calculate the gradient of the loss with respect to the parameters \(p\). Both use reverse mode, so the cost does not increase with the number of parameters.

Method 1: continuous adjoint

The continuous adjoint method ("optimise-then-discretise") first derives the adjoint ODE equations, and then solves them backwards in time with an ODE solver. First we solve the forwards problem, which gives a checkpointing struct. We then use the forward solution to calculate \(\frac{\partial \text{loss}}{\partial y_i}\) at each time point, and give this to the adjoint backwards pass. The backwards pass calculates the gradient of the loss with respect to the parameters.

    fn gradient_continuous(&self, param: &[T]) -> Vec<T> {
        let mut problem = self.problem.borrow_mut();
        let context = *problem.eqn().context();
        problem
            .eqn_mut()
            .set_params(&V::from_vec(param.to_vec(), context));
        let mut solver = problem.bdf::<LS>().unwrap();
        let (c, ys, _stop_reason) = match solver.solve_dense_with_checkpointing(&self.ts_data, None)
        {
            Ok(ys) => ys,
            Err(_) => return vec![f64::MAX / 1000.; param.len()],
        };
        let g_m = self.dloss_dy(&ys);
        let adjoint_solver = problem
            .bdf_solver_adjoint::<LS, _>(c, Some(solver), Some(1))
            .unwrap();
        match adjoint_solver.solve_adjoint_backwards_pass(self.ts_data.as_slice(), &[&g_m]) {
            Ok((soln, _)) => soln.as_ref().sg.get_batch(0).into_owned().clone_as_vec(),
            Err(_) => vec![f64::MAX / 1000.; param.len()],
        }
    }

The dloss_dy helper gives the matrix of \(\frac{\partial \text{loss}}{\partial y_i}\), with one column for each time point.

Method 2: reverse-mode AD of the solver steps

The second method ("discretise-then-optimise") uses the StepVjp trait. It does not solve an adjoint ODE. Instead, it pulls the loss gradient back through each step that the forward solver took, in reverse order. The step sizes, the orders and the accept/reject decisions of the forward solve are kept fixed. Thus the result is the gradient of the numerical solution, not an approximation of the gradient of the exact solution.

The code has the same shape as the continuous method. solve_dense_vjp_fwd solves the forwards problem and keeps the state after each step in a tape. We calculate \(\frac{\partial \text{loss}}{\partial y_i}\) as before. Then solve_dense_vjp_bkwd uses the tape to calculate the gradient with respect to the parameters.

    fn gradient_discrete(&self, param: &[T]) -> Vec<T> {
        let mut problem = self.problem.borrow_mut();
        let context = *problem.eqn().context();
        problem
            .eqn_mut()
            .set_params(&V::from_vec(param.to_vec(), context));
        let mut solver = problem.bdf::<LS>().unwrap();
        let (ys, tape) = match solver.solve_dense_vjp_fwd(&self.ts_data) {
            Ok(res) => res,
            Err(_) => return vec![f64::MAX / 1000.; param.len()],
        };
        let g_m = self.dloss_dy(&ys);
        match solver.solve_dense_vjp_bkwd(&tape, &g_m) {
            Ok(grad) => grad.clone_as_vec(),
            Err(_) => vec![f64::MAX / 1000.; param.len()],
        }
    }

The Gradient trait for argmin selects one of the two methods:

impl Gradient for Problem {
    type Gradient = Vec<T>;
    type Param = Vec<T>;

    fn gradient(&self, param: &Self::Param) -> Result<Self::Gradient, argmin_math::Error> {
        Ok(match self.method {
            GradientMethod::ContinuousAdjoint => self.gradient_continuous(param),
            GradientMethod::DiscreteAdjoint => self.gradient_discrete(param),
        })
    }
}

Comparing the two methods

In our main function we make the model and generate some synthetic data. Then we compare the two methods in two ways:

  1. We calculate the gradient at the initial parameters 1000 times with each method, and measure the mean time for one gradient.
  2. We use argmin's L-BFGS solver to fit the model to the data with each method, and measure the time for the full fit.
fn build_problem(k: T, c: T) -> OdeSolverProblem<Eqn> {
    OdeBuilder::<M>::new()
        .p([k, c])
        .sens_atol([1e-6])
        .sens_rtol(1e-6)
        .out_atol([1e-6])
        .out_rtol(1e-6)
        .build_from_diffsl(
            "
        in_i { k = 1.0, c = 0.1 }
        m { 1.0 }
        u_i {
            x = 1,
            v = 0,
        }
        F_i {
            v,
            -k/m * x - c/m * v,
        }
        ",
        )
        .unwrap()
}

/// The mean wall time of one call to `f`, over `n` calls after one warm-up call.
fn time_per_call(n: u32, mut f: impl FnMut()) -> Duration {
    f();
    let start = Instant::now();
    for _ in 0..n {
        f();
    }
    start.elapsed() / n
}

pub fn main() {
    let (k_true, c_true) = (1.0, 0.1);
    let t_data = (0..101)
        .map(|i| f64::from(i) * 40. / 100.)
        .collect::<Vec<f64>>();
    let ys_data = {
        let problem = build_problem(k_true, c_true);
        let mut solver = problem.bdf::<LS>().unwrap();
        solver.solve_dense(&t_data).unwrap().0
    };
    let make_cost = |method| Problem {
        ys_data: ys_data.clone(),
        ts_data: t_data.clone(),
        problem: RefCell::new(build_problem(k_true, c_true)),
        method,
    };
    let init_param = vec![k_true - 0.1, c_true - 0.01];
    let methods = [
        GradientMethod::ContinuousAdjoint,
        GradientMethod::DiscreteAdjoint,
    ];

    // benchmark one gradient evaluation at the initial parameters
    println!("Gradient at {init_param:?}:");
    let n = 1000;
    let mut times = Vec::new();
    let mut grads = Vec::new();
    for method in methods {
        let cost = make_cost(method);
        let time = time_per_call(n, || {
            cost.gradient(&init_param).unwrap();
        });
        let grad = cost.gradient(&init_param).unwrap();
        println!("  {method:?}: {grad:?}, {time:?} per gradient");
        times.push(time);
        grads.push(grad);
    }
    let rel_diff = grads[0]
        .iter()
        .zip(&grads[1])
        .map(|(a, b)| ((a - b) / b).abs())
        .fold(0.0, f64::max);
    println!("  Largest relative difference: {rel_diff:.2e}");
    println!(
        "  Speed-up of discrete over continuous: {:.2}x",
        times[0].as_secs_f64() / times[1].as_secs_f64()
    );

    // benchmark a full fit with each method
    for method in methods {
        let linesearch = MoreThuenteLineSearch::new().with_c(1e-4, 0.9).unwrap();
        let solver = LBFGS::new(linesearch, 7);
        let start = Instant::now();
        let res = Executor::new(make_cost(method), solver)
            .configure(|state| state.param(init_param.clone()).counting(true))
            .run()
            .unwrap();
        let time = start.elapsed();
        let state = res.state();
        let counts = state.get_func_counts();
        println!("\nFit with {method:?}:");
        println!("  time:           {time:?}");
        println!("  iterations:     {}", state.get_iter());
        println!("  cost evals:     {}", counts["cost_count"]);
        println!("  gradient evals: {}", counts["gradient_count"]);
        println!("  best cost:      {:e}", state.get_best_cost());
        println!("  best params:    {:?}", state.get_best_param().unwrap());
        println!("  termination:    {}", state.get_termination_status());
    }
    println!("\nTrue parameters: {:?}", vec![k_true, c_true]);
}

Run the example in release mode, because timings of a debug build are not useful:

cargo run --release -p mass-spring-fitting-adjoint --features diffsl-llvm17

The output is:

Gradient at [0.9, 0.09000000000000001]:
  ContinuousAdjoint: [-169.961431321948, -106.83268194215616], 2.031135ms per gradient
  DiscreteAdjoint: [-169.96068853944487, -106.80930261280977], 218.84µs per gradient
  Largest relative difference: 2.19e-4
  Speed-up of discrete over continuous: 9.28x

Fit with ContinuousAdjoint:
  time:           104.769459ms
  iterations:     13
  cost evals:     27
  gradient evals: 40
  best cost:      7.179238912566991e-25
  best params:    [0.9999999999999731, 0.10000000000000907]
  termination:    Solver converged

Fit with DiscreteAdjoint:
  time:           24.460875ms
  iterations:     12
  cost evals:     29
  gradient evals: 41
  best cost:      1.6127427301319806e-20
  best params:    [1.000000000003015, 0.09999999999754586]
  termination:    Solver converged

True parameters: [1.0, 0.1]

The times depend on your machine, but the ratio between the two methods is a better guide. For this problem, one gradient with reverse-mode AD of the steps is approximately 9 times faster than one gradient with the continuous adjoint. The continuous adjoint must solve a second ODE backwards in time, with its own adaptive steps and error control. Reverse-mode AD of the steps does not take new steps: it goes back through the steps of the forward solve that it kept in the tape. The full fit is approximately 4 times faster. The speed-up is smaller because the fit also calculates the loss, which costs the same for the two methods.

The two gradients agree to approximately \(2 \times 10^{-4}\) relative error. This difference comes from (a) the continuous adjoint method: it approximates the gradient of the exact ODE solution to the solver tolerances and (b) the discrete gradient method: we use an implicit solver so the linear solve for each VJP is only solved to the tolerances (an explicit solver will give an exact gradient up to floating point precision). The two fits converge to the true parameters, and they use a similar number of iterations.