package modelkit
authoring-estimators Authoring a third-party estimator
ModelKit extensions are ordinary OCaml modules. An estimator package depends on modelkit, implements a public protocol, and packages an immutable specification when it enters a pipeline. It does not depend on ModelKit's private Modelkit_* compilation units or on an execution backend.
Choose the protocol
Implement Modelkit.ESTIMATOR when fitting needs only features, targets, an optional sample-weight argument, and an explicit RNG. Implement Modelkit.METADATA_ESTIMATOR when fitting requests typed metadata such as weights, groups, or a progress callback. Classification implementations use integer Modelkit.Target.classification targets and regression implementations use float64 Modelkit.Target.regression targets.
In either protocol:
tis an immutable training specification andparamsis its inspectable parameter representation.fittedis a distinct type containing learned values and the admittedModelkit.Feature_schema.t.clonepreserves the specification's parameters; it does not copy fitted state.fitandpredictreturn typedModelkit.Error.tvalues for routine data, shape, validation, numerical, and compatibility failures.- every operation validates its schema and row-aligned inputs, and a fixed RNG stream produces deterministic results.
A metadata-aware regressor declares its needs before fitting:
let fit_request _specification =
Modelkit.Metadata.Request.create
~sample_weight:Modelkit.Metadata.Request.Required
~groups:Modelkit.Metadata.Request.Optional
~callback:Modelkit.Metadata.Request.Optional
()The pipeline validates all requests before any component fits and passes only the requested fields to the implementation. The estimator must still validate values it interprets. It must not retain fit metadata as an implicit input to a later prediction.
Package and identify the estimator
Create provenance once from nonblank package, version, and implementation identifiers, then pass it when packaging the specification:
let package specification =
let ( let* ) = Result.bind in
let* provenance =
Modelkit.Pipeline.provenance
~package:"acme-models"
~version:"1.2.0"
~implementation:"Robust_regressor"
in
Modelkit.Pipeline.metadata_estimator
~provenance
~name:"robust"
(module Robust_regressor)
specificationUse Modelkit.Pipeline.estimator for the ordinary estimator protocol. The result enters Modelkit.Pipeline.set_estimator and thereafter uses the same pipeline, nested composition, cross-validation, search, and optional parallel execution APIs as a built-in estimator. Search builders should construct a new immutable specification for every candidate and invoke the same packaging function.
Execution is owned by the workflow. A component should not create domains or thread pools internally. Applications opt into bounded fold or candidate execution by installing modelkit-parallel and passing its Modelkit_parallel.execution value to cross-validation or search.
Publish conformance checks
Package tests should run Modelkit.Conformance.Estimator.check or Modelkit.Conformance.Metadata_estimator.check against representative valid data. The fixture supplies the observations that generic code cannot infer from abstract target and prediction types: parameter equality, prediction length, and deterministic prediction equality. Assert Modelkit.Conformance.passed; use Modelkit.Conformance.failures and Modelkit.Conformance.issue_to_string for test-runner diagnostics.
Conformance is a protocol baseline, not a numerical validation suite. Component authors remain responsible for invalid-input, numerical-edge, parity, determinism, and platform tests appropriate to their algorithm. At least one integration test should exercise the packaged estimator through the workflows the package claims to support.
Provenance and portable artifacts
After fitting, Modelkit.Pipeline.artifact_report lists every fitted stage and the terminal estimator. Each component reports its optional provenance and Modelkit.Pipeline.serialization_support.Portable_artifact, Modelkit.Pipeline.serialization_support.External_artifact, or Modelkit.Pipeline.serialization_support.Unsupported. Provenance is descriptive identity; it never turns arbitrary behavior into a portable codec.
Ordinary public estimator adapters attach no codec. They remain fully usable for in-memory fitting and prediction, while Modelkit.Artifact.encode_regression or its classification counterpart returns a typed artifact error. ModelKit artifacts contain data rather than closures or marshalled OCaml values. An external codec therefore requires a separately reviewed, package-qualified, versioned data format and is not provided by an ambient registry.
For a reviewed terminal estimator implementing Modelkit.REGRESSOR, bind its data-only IO functions to Modelkit.Artifact.Codec.regression:
let codec =
Modelkit.Artifact.Codec.regression
~package:"acme-models" ~name:"Forecast" ~version:1
(module Forecast)
~encode:Forecast.encode_model
~decode:Forecast.decode_model
|> Result.get_ok
let package specification =
let ( let* ) = Result.bind in
let* provenance = Modelkit.Pipeline.provenance
~package:"acme-models" ~version:"1.2.0" ~implementation:"Forecast" in
Modelkit.Artifact.Codec.estimator ~name:"forecast" ~provenance codec specification
let load bytes =
Modelkit.Artifact.decode_regression
~decoders:[| Modelkit.Artifact.Codec.decoder codec |] bytesForecast.decode_model receives ~provenance and ~feature_schema before its payload argument. It validates its own payload and restores fitted state without training data or refitting. Native decoders must validate supported runtime versions and model/schema consistency and release acquired resources on errors or exceptions. Inference configuration can be captured when creating the codec used for decoding. Package identifiers and codec names are nonempty ASCII letters, digits, hyphens, underscores, or dots; modelkit is reserved. The integer codec version is independent of the component's package version.
For a regressor fitted outside Pipeline.fit, use Modelkit.Artifact.Codec.regression_pipeline to create a fitted inference pipeline directly. For example, using the same payload contract as above:
let wrap_fitted ~provenance fitted =
Modelkit.Artifact.Codec.regression_pipeline ~name:"forecast" ~provenance
~package:"acme-models" ~codec_name:"Forecast" ~version:1
(module Forecast) ~encode:Forecast.encode_model fittedThis retains the fitted value without invoking fit, predict, encode, or decode. The pipeline contains no preprocessing and takes its input/output schemas from the fitted regressor. The encoder runs only when saving; loading selects the matching codec's decoder explicitly. Preserve the package version that originally fitted the model in provenance, even after upgrading the package. The writer's current version is recorded separately in the outer artifact. Returning Pipeline.fitted rather than a trainable specification keeps this inference wrapper out of CV and search fitting paths.
Modelkit.Artifact.Codec.classification similarly binds a classifier and its class-label callback, with optional probability and decision dispatch. Its decoder additionally receives a bounded, distinct, ordered ~classes array and must restore that exact mapping. A generalized classification envelope can hold one or more classes; estimator-specific target restrictions remain the estimator's responsibility. The binary-specific APIs require exactly two.
The decoder list is local to the load call. Missing or duplicate selections, unknown codec versions, malformed framing/checksums, invalid schemas/classes, and task mismatches fail with typed errors. The core validates the entire envelope before an external callback. It does not interpret opaque external payloads or extend its built-in safe-reader guarantee to them. Applications select trusted codec code and follow its artifact trust policy; a checksum detects corruption and does not establish authenticity.
Modelkit.Pipeline.artifact_supported accepts both built-in and explicitly attached external codecs; Modelkit.Pipeline.portable_artifact_supported accepts only built-in portable codecs. The current extension supports external terminal estimators surrounded by codec-supported built-in preprocessing. External transformer codecs, metadata-aware terminal codecs, and nested composition remain unsupported and fail by component name.
Existing built-in regression and binary writers retain container version one. External terminals use version two, which records package-qualified codec identity, exact format version, producer provenance, and classification labels. Modelkit.Artifact.encode_classification always writes the generalized task in version two. Modelkit.Artifact.decode_classification accepts that task and legacy binary artifacts; use it for generalized artifacts even when they have two classes. The binary loader continues to require the binary task tag.
The separately compiled test/public_codec_consumer library uses public APIs only to demonstrate weighted pipeline round trips, explicit version selection, class-order preservation, bounded-reader failures, and committed version-two golden artifacts.
The repository's separately built test/public_consumer library is the executable reference for this guide. Its one metadata-aware estimator module is used unchanged by conformance checks, nested composition, two-domain cross-validation, randomized search, and artifact-support reporting while depending only on the public Modelkit namespace.