diff --git a/gpjax/fit.py b/gpjax/fit.py index 371c3fa12..4280c7e6c 100644 --- a/gpjax/fit.py +++ b/gpjax/fit.py @@ -15,6 +15,7 @@ import functools import typing as tp +import warnings import equinox as eqx import jax @@ -22,7 +23,7 @@ import jax.numpy as jnp import jax.random as jr import optax as ox -from scipy.optimize import minimize +from scipy.optimize import OptimizeWarning, minimize from gpjax.dataset import Dataset from gpjax.natural_gradients import ( @@ -236,11 +237,27 @@ def scipy_wrapper(x0): fun=scipy_wrapper, x0=x0, jac=True, + method="L-BFGS-B", callback=lambda X: history.append(scipy_wrapper(X)[0]), - options={"maxiter": max_iters, "disp": verbose}, + options={"maxiter": max_iters}, ) history = jnp.array(history) + # L-BFGS-B has no verbosity option in SciPy, so report the outcome here + # rather than handing the solver an option it silently ignores. + if verbose: + print( + f"L-BFGS-B stopped after {len(history) - 1} iterations with " + f"objective {float(history[-1]):.6g}: {result.message}" + ) + + # A solver that gave up leaves a model that is no better than its starting + # point, which is easy to mistake for a converged fit. + if not result.success: + warnings.warn( + f"SciPy did not converge: {result.message}", OptimizeWarning, stacklevel=2 + ) + # convert back to pytree with JAX arrays params = scipy_to_jnp(result.x) diff --git a/tests/test_fit.py b/tests/test_fit.py index 732f25bef..2da67b3e8 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -39,10 +39,7 @@ ) from gpjax.kernels import RBF from gpjax.likelihoods import Gaussian -from gpjax.mean_functions import ( - AbstractMeanFunction, - Constant, -) +from gpjax.mean_functions import Constant from gpjax.objectives import ( conjugate_mll, dual_elbo, @@ -52,7 +49,6 @@ PositiveReal, val, ) -from gpjax.typing import Array from gpjax.variational_families import ( CollapsedVariationalGaussian, DualVariationalGaussian, @@ -61,15 +57,12 @@ import jax.numpy as jnp import jax.random as jr import jax.tree_util as jtu -from jaxtyping import ( - Float, - Num, -) import numpy as np import optax as ox import paramax import pytest import scipy +from scipy.optimize import OptimizeResult from tests._reference.conjugate_svgp import conjugate_optimum @@ -166,6 +159,33 @@ def mse(model, data): assert trained_model.bias == 1.0 +def test_fit_scipy_uses_lbfgsb(monkeypatch): + # Create dataset: + X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) + y = 2.0 * X + 1.0 + D = Dataset(X, y) + + model = LinearModel(weight=1.0, bias=1.0) + + # Define loss function: + def mse(model, data): + pred = model(data.X) + return jnp.mean((pred - data.y) ** 2) + + # Record the arguments fit_scipy hands to SciPy without running an optimiser: + seen = {} + + def fake_minimize(*args, **kwargs): + seen.update(kwargs) + return OptimizeResult(x=kwargs["x0"], fun=0.0, success=True, message="ok") + + monkeypatch.setattr(sys.modules["gpjax.fit"], "minimize", fake_minimize) + fit_scipy(model=model, objective=mse, train_data=D, max_iters=5, verbose=False) + + # The docstring promises L-BFGS-B, so the method must not be left to SciPy: + assert seen["method"] == "L-BFGS-B" + + def test_fit_lbfgs_simple(): # Create dataset: X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) @@ -330,25 +350,7 @@ def test_fit_scipy_error_raises() -> None: X=jnp.array([[0.0]], dtype=jnp.float64), y=jnp.array([[0.0]], dtype=jnp.float64) ) - # build crazy mean function so that opt fails - class CrazyMean(AbstractMeanFunction): - def __call__(self, x: Num[Array, "N D"]) -> Float[Array, "N O"]: - return jnp.heaviside(x, 100.0) - - # Define GP model with crazy mean function: - prior = Prior(kernel=RBF(), mean_function=CrazyMean()) - likelihood = Gaussian() - posterior = prior * likelihood - - with pytest.raises(scipy.optimize.OptimizeWarning): - fit_scipy( - model=posterior, - objective=conjugate_mll, - train_data=D, - max_iters=10, - ) - - # also check fails if no given enough steps + # a solver that stops at its iteration limit reports that it did not converge prior = Prior(kernel=RBF(), mean_function=Constant()) likelihood = Gaussian() posterior = prior * likelihood