Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions gpjax/fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@

import functools
import typing as tp
import warnings

import equinox as eqx
import jax
from jax.flatten_util import ravel_pytree
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 (
Expand Down Expand Up @@ -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)

Expand Down
58 changes: 30 additions & 28 deletions tests/test_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -52,7 +49,6 @@
PositiveReal,
val,
)
from gpjax.typing import Array
from gpjax.variational_families import (
CollapsedVariationalGaussian,
DualVariationalGaussian,
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading