This notebook shows how to wrap a trained sklearn estimator and a small JAX model as xrtoolz Layer-1 operators with ModelOp, then compose them in a Graph together with an RMSE metric.
Key points (per design decision D4):
xrtoolz.inference.ModelOpis framework-agnostic — it never importssklearn,jax,torch, orequinoxat module load time.SklearnModelOpandJaxModelOpare thin subclasses; backend imports happen lazily on first use.Inputs are
xr.DataArray/xr.Datasetwith afeaturedim; outputs come back asxr.DataArraycarrying the input’s non-feature coordinates.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
"xrtoolz[inference] @ git+https://github.com/jejjohnson/geotoolz@main#subdirectory=packages/xrtoolz",
],
check=True,
)
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import importlib.util
try:
from IPython import get_ipython
ipython = get_ipython()
except ImportError:
ipython = None
if ipython is not None and importlib.util.find_spec("watermark") is not None:
ipython.run_line_magic("load_ext", "watermark")
ipython.run_line_magic(
"watermark",
"-v -m -p numpy,xarray,scikit-learn,jax,equinox,xrtoolz",
)
else:
print("watermark extension not installed; skipping reproducibility readout.")
from __future__ import annotations
import numpy as np
import xarray as xr
rng = np.random.default_rng(0)1. Synthetic data¶
Build a small regression dataset as an xr.DataArray with (sample, feature) dims and a matching target.
n_samples, n_features = 256, 4
x = rng.standard_normal((n_samples, n_features))
true_w = np.array([1.5, -2.0, 0.5, 0.0])
y = x @ true_w + 0.1 * rng.standard_normal(n_samples)
X = xr.DataArray(
x,
dims=('sample', 'feature'),
coords={'sample': np.arange(n_samples),
'feature': ['x0', 'x1', 'x2', 'x3']},
name='X',
)
Y = xr.DataArray(y, dims=('sample',), coords={'sample': np.arange(n_samples)},
name='Y')
X2. Wrap a fitted scikit-learn model with SklearnModelOp¶
from sklearn.linear_model import LinearRegression
from xrtoolz.inference import SklearnModelOp
lr = LinearRegression().fit(x, y)
sk_op = SklearnModelOp(lr)
sk_opSklearnModelOp(model='<model>', method='predict', feature_dim='feature', output_name='prediction', output_dim='output')y_hat_lr = sk_op(X)
y_hat_lrNotice that the output is an xr.DataArray on the same sample axis as the input. The model itself was never serialized; get_config() captures only the wrapper config:
sk_op.get_config(){'model': '<model>',
'method': 'predict',
'feature_dim': 'feature',
'output_name': 'prediction',
'output_dim': 'output'}3. A tiny JAX model wrapped with JaxModelOp¶
We define a minimal MLP as a plain pytree-callable. JaxModelOp JIT-compiles it on first use; jax is imported lazily.
import jax
import jax.numpy as jnp
from xrtoolz.inference import JaxModelOp
def init_mlp(key, in_dim, hidden, out_dim):
k1, k2 = jax.random.split(key)
return {
'W1': 0.1 * jax.random.normal(k1, (in_dim, hidden)),
'b1': jnp.zeros(hidden),
'W2': 0.1 * jax.random.normal(k2, (hidden, out_dim)),
'b2': jnp.zeros(out_dim),
}
params = init_mlp(jax.random.PRNGKey(0), n_features, 16, 1)
def mlp(params, x):
h = jnp.tanh(x @ params['W1'] + params['b1'])
return (h @ params['W2'] + params['b2']).squeeze(-1)
# Train for a few steps with plain SGD on the squared loss.
def loss(params, x, y):
pred = mlp(params, x)
return jnp.mean((pred - y) ** 2)
grad_fn = jax.jit(jax.grad(loss))
lr_rate = 0.05
for _ in range(200):
g = grad_fn(params, x, y)
params = jax.tree_util.tree_map(lambda p, gp: p - lr_rate * gp, params, g)
# Bind params and wrap. The wrapped callable takes a 2-D array.
def predict(x_arr):
return mlp(params, x_arr)
jax_op = JaxModelOp(predict, jit=True)
jax_opJaxModelOp(model='<model>', method=None, feature_dim='feature', output_name='prediction', output_dim='output', jit=True)y_hat_mlp = jax_op(X)
y_hat_mlp4. Compose both wrappers in a single Graph with RMSE¶
Both ModelOp instances are full Layer-1 operators, so they slot into the functional Graph API alongside any other operator — here the RMSE metric from xrtoolz.metrics.
from xrtoolz import Graph, Input, Operator
from xrtoolz.metrics.operators import RMSE
# RMSE is a two-input pixel metric over a dataset variable. Wrap each
# prediction + the reference into a small Dataset so it can be consumed.
class AsDataset(Operator):
"""Pack a prediction and reference DataArray into a Dataset."""
def __init__(self, name: str = 'y'):
self.name = name
def _apply(self, da):
return da.rename(self.name).to_dataset()
def get_config(self):
return {'name': self.name}
to_ds = AsDataset(name='y')
x_in = Input('X')
y_in = Input('Y')
rmse_op = RMSE(variable='y', dims='sample')
lr_pred = sk_op(x_in)
mlp_pred = jax_op(x_in)
lr_rmse = rmse_op(to_ds(lr_pred), to_ds(y_in))
mlp_rmse = rmse_op(to_ds(mlp_pred), to_ds(y_in))
graph = Graph(
inputs={'X': x_in, 'Y': y_in},
outputs={
'lr_pred': lr_pred,
'mlp_pred': mlp_pred,
'lr_rmse': lr_rmse,
'mlp_rmse': mlp_rmse,
},
)
print(graph.describe())Graph (2 inputs, 4 outputs):
Inputs: ['X', 'Y']
[2] AsDataset(name='y') ← ['Y']
[3] AsDataset(name='y') ← ['Y']
[4] JaxModelOp(model='<model>', method=None, feature_dim='feature', output_name='prediction', output_dim='output', jit=True) ← ['X']
[5] SklearnModelOp(model='<model>', method='predict', feature_dim='feature', output_name='prediction', output_dim='output') ← ['X']
[6] AsDataset(name='y') ← ['<node 125852674600912>']
[7] AsDataset(name='y') ← ['<node 125849727031952>']
[8] RMSE(variable='y', dims='sample') ← ['<node 125849730559312>', '<node 125849727648096>']
[9] RMSE(variable='y', dims='sample') ← ['<node 125849726853008>', '<node 125849726933920>']
Outputs: ['lr_pred', 'mlp_pred', 'lr_rmse', 'mlp_rmse']
results = graph(X=X, Y=Y)
{k: float(v.values) if v.shape == () else v for k, v in results.items() if 'rmse' in k}{'lr_rmse': 0.10134100923089427, 'mlp_rmse': 0.1696163804879099}5. The wrapper is fully introspectable¶
Both wrappers expose JSON-serializable configs (the model itself is referenced as the literal string "<model>"):
import json
print(json.dumps([sk_op.get_config(), jax_op.get_config()], indent=2))[
{
"model": "<model>",
"method": "predict",
"feature_dim": "feature",
"output_name": "prediction",
"output_dim": "output"
},
{
"model": "<model>",
"method": null,
"feature_dim": "feature",
"output_name": "prediction",
"output_dim": "output",
"jit": true
}
]