Surface Fitting with Kernel Methods¶
The rgpycrumbs.surfaces module provides high-performance, differentiable surface models using JAX. These models are designed for constructing Potential Energy Surfaces (PES) and other multidimensional functions, supporting both standard observations and gradient-enhanced data.
flowchart LR
OBS[x, y, optional gradients] --> MODEL[get_surface_model]
MODEL --> OPT[hyperparameter fit]
OPT --> PRED[predict / predict_var]
PRED --> PLOT[chemparseplot contourf]
Note
Callers in chemparseplot may opt into observation thinning via
SurfaceFitConfig(auto_thin=True) before the model is built. That step is
off by default and lives above this module.
Available Models¶
A variety of kernel-based models are provided via a unified interface:
TPS/RBF: Thin Plate Splines, standard for smooth interpolation.
Matérn 5/2: A stationary kernel with finite differentiability.
IMQ: Inverse Multi-Quadratic kernel, often more stable for large spans.
Gradient-Enhanced: Versions of Matérn, Squared Exponential (SE), RQ, and IMQ that incorporate energy gradients directly into the covariance structure.
Nystrom Gradient IMQ: A memory-efficient approximation for large datasets.
Uncertainty and Variance¶
Every model in surfaces.py implements a predict_var(x_query) method. This calculates the posterior predictive variance, providing a measure of uncertainty:
Interpretation: The variance represents the model’s confidence. At training points (and within the kernel’s length scale), the variance is low. In data-sparse regions, it reverts toward the prior variance (e.g., \(1/\epsilon\) for IMQ or \(1.0\) for Matérn).
Optimization: Fits choose length scales (\(l\), \(\epsilon\)) and noise scalars by Maximum Likelihood Estimation (MLE). The gradient inverse multiquadric fit is a Maximum A Posteriori (MAP) estimate. Its prior is a gamma distribution on \(\epsilon\).
Variance Windowing and Chunking¶
To prevent Out-Of-Memory (OOM) errors during the evaluation of large grids (e.g., 2D slice visualizations), both the prediction and variance calls are internally chunked.
model = GradientMatern(x_obs, y_obs, gradients=g_obs)
# Evaluates in chunks of 500 query points by default
z_preds = model(x_grid, chunk_size=1000)
z_vars = model.predict_var(x_grid, chunk_size=1000)
This “windowed” evaluation ensures that the large \(N_{query} \times N_{train}\) cross-covariance matrices do not exhaust system memory.
Numerical Stability¶
Gradient-enhanced models use auto-differentiation (via jax.grad and jax.jacfwd) to construct the full \((D+1)N \times (D+1)N\) covariance matrix.
Cholesky Fallback: The
safe_cholesky_solveutility adds roundoff jitter scaled to the covariance. It checks the factor for non-finite values, sincejax.numpy.linalg.choleskyreturns NaNs instead of raising.Float Precision: By default, models use
float32for performance and compatibility with visualization backends, butjax_enable_x64can be toggled if higher precision is required.
Fit Defaults¶
The surface fits take these defaults from rgpycrumbs.surfaces._hyperparameters.
Length scales: Fits start the length scale at the median distance between distinct inputs. The inverse multiquadric models start \(\epsilon\) the same way. Garreau, Jitkrittum and Kanagawa analyse this median heuristic.
Optimizer: Fits with
optimize=Truerun SciPy’sL-BFGS-Bon the log-parameters. It keeps the last point that its line search accepted.Priors: Fits maximize the marginal likelihood. The
GradientIMQfit adds a gamma prior of shape 2 on \(\epsilon\). Chung et al. propose that shape because the prior vanishes at zero. The prior peaks at the starting value of \(\epsilon\).Rational quadratic:
GradientRQfits start the shape \(\alpha\) at 1. The kernel is a gamma mixture of squared-exponential kernels. Shape 1 makes that gamma distribution exponential.Smoothing: A caller’s
smoothingis the noise variance of fixed fits and the start of optimized ones. TheGradientIMQfit caps its fitted noise at that value. Without asmoothing, or with zero, the fits treat the data as exact. Fixed fits then use the roundoff jitter as the noise. Optimized fits start the noise at the largest prior variance. The first covariance matrix then has a condition number of at most \(n + 1\).Roundoff jitter: The diagonal shift is \(\gamma_{n+1} = (n+1)u/(1-(n+1)u)\) times the largest covariance entry. Here \(u\) is the unit roundoff of the working precision. The shift bounds the entrywise backward error of a Cholesky factorization. Higham states this bound as Theorem 10.3.
Kernel guards: Three guards come from the float32 machine epsilon
eps = 2**-23. That is the spacing of float32 numbers at one, so inputs of order one resolve no shorter length. The squared-exponential kernel clamps its length scale ateps. The thin-plate and Matérn kernels use \(r = \sqrt{d^2 + \mathrm{eps}^2}\). So \(r\) stays positive at coincident points. In float32 that sum equals \(d^2\) for every \(d^2 \geq 2^{-21}\). The1e-12used before was a no-op in float32 for every \(d^2 \geq 2^{-15}\). The rational-quadratic kernel addseps**2to \(2 \alpha l^2\). It then stays defined at coincident points when that product underflows. The1e-6used before changed that kernel by half a percent at \(l = 0.01\) and by half at \(l = 10^{-3}\).Gradient noise: With
noise_per_obs,GradientIMQspreads each energy noise over the gradients at that point. Each gradient component keeps the energy’s ratio of noise to prior variance. Its noise then has the units of a gradient variance.Nystrom fits: With
optimize=True,NystromGradientIMQfits \(\epsilon\) and the noise on its inducing points. The fit uses theGradientIMQprior and noise cap. Aseedargument picks the random inducing subset, and its default of 42 only makes that subset reproducible.
Troubleshooting¶
“Out of memory” during surface fitting¶
Problem: JAX runs out of GPU/CPU memory when fitting large datasets.
Solution:
Use Nystrom approximation for datasets with >1000 points:
from rgpycrumbs.surfaces import get_surface_model model = get_surface_model("grad_imq_ny")(x_obs, y_obs, gradients=g_obs, n_inducing=200)
Reduce
n_inducingparameter (default: 100)Use
float32precision instead offloat64
Cholesky decomposition fails¶
Problem: safe_cholesky_solve reports numerical instability.
Solution:
Increase the
smoothingparameter (adds jitter to diagonal):model = GradientMatern(x_obs, y_obs, gradients=g_obs, smoothing=1e-3)Check for duplicate or near-duplicate training points
Normalize input coordinates to [0, 1] range
Variance predictions are all zero¶
Problem: predict_var() returns zeros everywhere.
Solution:
Verify the model was fitted successfully (check
model.lsormodel.epsilon)Ensure query points are not exactly at training points (variance should be
noisethere)Check that
smoothingparameter is not too large
Length scale optimization fails¶
Problem: Optimizer reports “optimization failed” or length scales are extreme.
Solution:
Provide better initial guesses:
model = GradientMatern(x_obs, y_obs, ls=0.5, smoothing=1e-4)Check data scaling - inputs should be O(1) magnitude
Try a different kernel (TPS is more stable for some problems)
Gradient-enhanced model slower than expected¶
Problem: Fitting with gradients is much slower than standard RBF.
Solution:
This is expected - gradient models have \((D+1)N \times (D+1)N\) covariance
Use Nystrom approximation for large datasets
Consider using standard (non-gradient) models if gradients are noisy
The first fit at each number of points compiles its
jax.jitfunctions, and later fits of that size reuse them
API Reference¶
For detailed method signatures, see the Surfaces API Reference.