Status: not built (phase D of
boundaries.md§4).pipekit_array.inferencedoes not exist in pipekit-array 0.3.1, so every call toModelOpbelow isproposed. The weight-blob wrappers of ADR A8 were built outside pipekit-array:pipekit_jax.JaxModelOp, andEquinoxModelOpandKerasModelOpin pipekit-train, so a Keras or Equinox model already has an operator. The generic wrapper for scikit-learn, torch and plain functions has not. Two shipped pieces cover part of the ground:BatchAlong(pipekit_array.operators) splits a carrier for chunked inference, andEstimator(pipekit_array.bridges.sklearn,[sklearn]) fits and applies a scikit-learn-style estimator on a named carrier.
ModelOp is the framework-agnostic trained-model wrapper.
It holds a callable (a NumPy function, an sklearn predict, a raw torch nn.Module, a Keras model, …) and calls it on the input.
# proposed (phase D)
from pipekit_array.inference import ModelOp
# Wrap a Keras model; method defaults to "__call__".
op = ModelOp(model=keras_model)
y = op(x) # x: a NumPy, torch or JAX array, as the model expects
# Wrap an sklearn estimator's predict method.
op = ModelOp(model=sklearn_clf, method="predict")
y_hat = op(x_test) # (N, D) → (N,)Why this exists¶
There are three reasons:
It was to close the train-to-serve loop for pipekit-train. The Lightning and Keras adapters were to return
ModelOpfromloop.run(). Lightning was dropped (pipekit-train D15), and the Keras backend returns its ownpipekit_train.backends.keras.KerasModelOp, whose weights round-trip through a registry as a byte-stable blob (pipekit-train D20), so no pipekit-train backend waits onModelOp.It is the natural home for sklearn and NumPy-ML pipelines. A lot of working code wraps a fitted
RandomForestClassifieror a trained sklearn pipeline, andModelOpis the one-line shim that makes them compose into a pipekitSequential.It generalises
pipekit_array.BatchAlong’sinnerargument.BatchAlong(ModelOp(big_model), size=32, dim="sample")is the canonical “stream a large array through a model in chunks” idiom.
The split with pipekit_jax.JaxModelOp is ADR A8: the Equinox weight-blob round trip lives in pipekit-jax (which carries the Orbax dependency), and pipekit-array’s ModelOp stays generic and Orbax-free.
Contract¶
Constructor¶
ModelOp(
model: Any, # the trained model object
method: str = "__call__", # method to invoke on `model`
batch_size: int | None = None, # if set, batch automatically
method_kwargs: dict | None = None, # forwarded to model.<method>(x, **kwargs)
)model: any callable or object with the named method.
There is no isinstance check, and the duck typing is intentional.
If getattr(model, method) is not callable at construction time, it raises TypeError immediately.
method: the name of the method to call.
It defaults to "__call__", which is the right shape for raw Keras, PyTorch and Equinox modules; sklearn estimators use "predict", "predict_proba" or "transform".
batch_size: if set, the model call is wrapped in BatchAlong(self._inner_op, size=batch_size, dim=...) internally.
It is a convenience shorthand, equivalent to BatchAlong(ModelOp(model, method), size=..., dim=...).
BatchAlong cuts a named dim of a named carrier, so the design still has to say which dim, or how a raw array maps to one.
method_kwargs: passed through on every call.
They are useful for models with training=False flags, dropout suppression and the like.
Keys must be strings and values must be JSON-serialisable, because they are re-emitted in get_config().
_apply(x)¶
def _apply(self, x):
fn = getattr(self.model, self.method)
return fn(x, **(self.method_kwargs or {}))If batch_size is set, it is the equivalent batched call.
There is no Array API dispatch, because the model owns the backend; ModelOp’s job is plumbing, not numerics.
get_config()¶
{
# The model object is the artifact. We don't serialise it; the
# config records the call shape only.
"model": {
"class": type(self.model).__name__,
"module": type(self.model).__module__,
# Optionally a content hash if the model exposes one (sklearn
# doesn't; a PyTorch state_dict can be hashed; this is opt-in
# per backend).
},
"method": self.method,
"batch_size": self.batch_size,
"method_kwargs": dict(self.method_kwargs or {}),
}Note: the trained weights are not in the config.
ModelOp round-trips the call shape, and the weights are the user’s artifact to keep out of band.
For Equinox, use pipekit_jax.JaxModelOp, which does round-trip weights through pipekit-experiment.ModelRegistry.
compute_output_signature(sig)¶
It returns None, because the operator can’t know the model’s output shape without running it, so Sequential.summary prints ? for the output.
Override it per backend in user code if shape inference matters (a Keras model can report its own via model.compute_output_shape).
forbid_in_yaml¶
forbid_in_yaml: ClassVar[bool] = TrueThe model itself isn’t YAML-round-trippable (the trained weights are the artifact, not part of the config).
The check_pickleable lint catches ModelOp instances in ProcessMap-deployable pipelines and reminds the user to make sure the model pickles.
Use cases¶
Sklearn classifier in a pipekit pipeline¶
# proposed (phase D)
from pipekit_array.inference import ModelOp
# proposed (phase C)
from pipekit_array.qc import AssertNoNaN
pipe = AssertNoNaN() | ModelOp(rf_classifier, method="predict_proba")
probs = pipe(X_test) # (n_samples, n_features) → (n_samples, n_classes)On a named carrier, Estimator(rf_classifier, sample_dims=..., method="predict_proba") already does this today, fitting by dim name (pipekit_array.bridges.sklearn).
Keras models after pipekit-train¶
The Keras backend of pipekit-train returns a KerasModelOp, not a ModelOp: it needs Keras to write and reload the weights, and pipekit-array takes no backend dependency (A8). ModelOp(model=keras_model, method_kwargs={"training": False}) remains the way to wrap a Keras model that pipekit-train did not train, when its weights are kept out of band.
Large-input batched inference¶
# proposed (phase D)
op = ModelOp(big_torch_model, method="forward", batch_size=64)
preds = op(huge_input_array) # batches internallyThis is equivalent to:
# today (pipekit-array): BatchAlong; proposed (phase D): ModelOp
op = BatchAlong(ModelOp(big_torch_model, method="forward"), size=64, dim="sample")The batch_size= constructor shorthand is purely for ergonomics; under the hood it is the explicit BatchAlong composition.
Per-backend notes¶
PyTorch:
model.eval()andtorch.no_grad()are not automatic. The user is responsible for putting the model in eval mode and disabling autograd if they want inference semantics. The docstring should say so, and cite a one-lineevalTap as the pattern.Keras 3:
model(x, training=False)is the inference-time signature, so passmethod_kwargs={"training": False}.sklearn:
method="predict"for the dense prediction,"predict_proba"for the probabilistic one and"transform"for transformers. The model must be fitted beforeModelOpis constructed; we don’t check, and sklearn raisesNotFittedErroron the first call.JAX (
jax.numpyarrays): raw JAX functions work (ModelOp(model=lambda x: ...)); for aneqx.Module, usepipekit_jax.JaxModelOpinstead, so the weights round-trip.
Failure modes¶
| Symptom | Likely cause |
|---|---|
TypeError: model.<method> is not callable | wrong method name; check dir(model) |
NotFittedError (sklearn) | model not fitted before wrapping |
RuntimeError: leaf Variable that requires grad ... | torch model not in eval() + no_grad() |
Pipeline can’t pickle for ProcessMap | model not pickleable; switch to ThreadMap or pin |
All four should be documented in the operator’s docstring, each with its one-line fix.