Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
68 changes: 68 additions & 0 deletions docs/guides/mlproject-export.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# MLproject Export

`chapkit mlproject export` is the reverse of [`chapkit mlproject migrate`](mlproject-migrate.md): it reads a chapkit service module (usually `main.py`) and writes the `MLproject` that [`chapkit mlproject run`](mlproject-runner.md) serves as the same service. Use it when a model ships a hand-written chapkit service but should also run from its MLproject, for example with `chapkit mlproject run .` or `chap eval --run-config.as-chapkit`.

`main.py` stays the source of truth. The MLproject is generated from it, and `--check` keeps the two from drifting.

## Quick Start

```bash
chapkit mlproject export # reads ./main.py, writes ./MLproject
chapkit mlproject export path/to/main.py
chapkit mlproject export --check # write nothing; exit 1 when MLproject is stale
```

The module is executed the way the service itself would run it, from its own directory, so imports and relative paths in `main.py` work. Output it prints while building the app goes to stderr.

Add the check to CI or `make lint` so a change to `main.py` without regenerating the MLproject fails the build:

```makefile
lint:
uv run chapkit mlproject export --check
```

## What It Reads

The command finds the objects by type, so their names do not matter:

| In the module | Becomes in the MLproject |
| --- | --- |
| The `MLServiceInfo` | `name`, `version`, `target`, `supported_period_type`, `required_covariates`, `allow_free_additional_continuous_covariates`, `requires_geo`, `min_prediction_periods`, `max_prediction_periods`, `hpo_search_space`, and `meta_data` (display name, description, author fields, URLs) |
| The `BaseConfig` subclass | `user_options`: one JSON Schema property per field, with its type, constraints, default and description |
| The `ShellModelRunner` | `entry_points.train` / `predict`, with runner placeholders turned back into MLproject parameters (`{data_file}` becomes `{train_data}`, `{output_file}` becomes `{out_file}`, and so on), plus `adapters` |
| The `ArtifactHierarchy` | `name`, when it slugifies to the service id; otherwise the id is used |

Only `ShellModelRunner` services can be exported, because an MLproject runs train and predict as shell commands. If the module defines several config classes, pick one with `--config NAME`.

`prediction_periods` and `additional_continuous_covariates`, which every chapkit config has, are left out of `user_options` unless the config changes their default or what they accept (for example `prediction_periods: int = Field(default=3, ge=2, le=6)`).

Literal braces in a runner command (`{{` / `}}`) are escaped once more in the MLproject, because `chapkit mlproject run` formats the command twice: first the MLproject parameters, then the runner's own placeholders.

### Config Layout

`ShellModelRunner` writes a flat `config.yml` by default, while `chapkit mlproject run` writes chap-core's nested layout. When the runner uses the flat layout, the generated header says so:

```
# The scripts read a flat config.yml: run with `chapkit mlproject run . --config-format flat`.
```

## The Check

`--check` fails in two cases:

1. The MLproject differs from what `export` would write now. The diff is printed.
2. The MLproject matches, but `chapkit mlproject run` would read it as a different service. The file is parsed with chapkit's own MLproject reader, and the served `/api/v1/info`, the config options with their defaults and the values each accepts, the runner commands and the adapters are compared with the module. This catches a generator bug that a matching text diff would hide, and contract differences that come from how `run` reads an MLproject. For example, a service without `author_note` fails, because `run` serves the description in its place.

## Safety

The generated file starts with a `Generated from ... by chapkit mlproject export` header. `export` refuses to overwrite an MLproject without it, so a hand-written file is not lost. Pass `--force` to replace it once; from then on it is regenerated freely.

## Options

| Option | Effect |
| --- | --- |
| `PATH` | Service module to read (default: `main.py`). |
| `-o`, `--output FILE` | MLproject to write (default: the `MLproject`, `MLproject.yaml` or `MLproject.yml` next to the module, else a new `MLproject`). |
| `--check` | Write nothing; exit 1 when the MLproject is stale or would be read as a different service. |
| `--config NAME` | Config class to use when the module defines several. |
| `--force` | Overwrite an MLproject that was not generated by this command. |
50 changes: 49 additions & 1 deletion docs/guides/mlproject-runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ chapkit mlproject run /path/to/my_mlproject/MLproject.yaml

This parses the `MLproject` file, translates the entry-point commands to chapkit's workspace conventions, builds a FastAPI service with `/api/v1/ml/$train` and `/$predict` endpoints, and serves on `127.0.0.1:9090` by default. Override host/port with `--host` and `--port`. If the port is already taken, `chapkit mlproject run` stops with an error before starting anything.

Nothing is written to your MLproject directory: configs, artifacts and jobs live in memory, and each train/predict runs in a temporary copy of the project.
Nothing is written to your MLproject directory: configs, artifacts and jobs live in memory (configs and artifacts can go in a SQLite file of your choosing with `--database`, see [Service Options](#service-options)), and each train/predict runs in a temporary copy of the project.

A minimal R MLproject like `dhis2-chap/minimalist_example_r`:

Expand Down Expand Up @@ -68,6 +68,51 @@ The `--param NAME=FILENAME` flag is repeatable. Overrides win over the canonical

---

## Service Options

These options cover what a hand-written `main.py` service can set and an MLproject cannot. All of them are optional; without any, the service keeps its state in memory and writes `config.yml` in chap-core's layout.

| Option | Default | Effect |
| --- | --- | --- |
| `--config-format chap_core\|flat` | `chap_core` | Layout of the `config.yml` your scripts read (see below). |
| `--database PATH` | in memory | Keep configs and trained models (artifacts) in this SQLite file so they survive a restart; predict still works on a model trained before the restart. Job history is not stored and starts empty after a restart. The file and its directory are created if missing, and migrations run on startup. A relative path is relative to where you run the command. |
| `--keepalive-interval SECONDS` | `10` | Seconds between keepalive pings once registered with chap-core. Only applies when registration is configured ([Integration with chap-core](#integration-with-chap-core)). |
| `--log-level LEVEL` | `LOG_LEVEL`, then `info` | `debug`, `info`, `warning`, `error` or `critical`. |

The startup output shows the config layout and where state is stored:

```
config: config.yml (chap_core layout)
storage: in memory
```

### Config layout

By default `config.yml` follows chap-core's `ModelConfiguration` shape, the same file chap-core gives MLproject models it runs itself, and the one `chapkit mlproject migrate` generates services for:

```yaml
user_option_values:
n_lags: 3
cell: gru
additional_continuous_covariates: []
prediction_periods: 3
```

Scripts written for a hand-written chapkit service usually read a flat file instead. `--config-format flat` writes every option at the top level:

```yaml
n_lags: 3
cell: gru
additional_continuous_covariates: []
prediction_periods: 3
```

### Artifacts

Artifacts belong to a hierarchy named after the MLproject's `name` (as a Python identifier, e.g. `my-model` becomes `my_model`), with the levels `ml_training_workspace` (trained models) and `ml_prediction`. This matches the services `chapkit mlproject migrate` and `chapkit init` generate.

---

## Model Contract from the MLproject

`/api/v1/info` serves the same contract chap-core reads from an MLproject (`ModelTemplateConfigV2` in chap-core), so chap-core sees the model the same way whether it runs the MLproject itself or talks to `chapkit mlproject run`:
Expand Down Expand Up @@ -312,6 +357,8 @@ chapkit mlproject run ./my_mlproject --host 0.0.0.0 --port 9090 \

The shared registration secret is only read from `SERVICEKIT_REGISTRATION_KEY`, so it never appears in the process list or shell history.

Once registered, the service pings chap-core every 10 seconds to stay listed. Change that with `--keepalive-interval SECONDS`.

---

## Limitations and When to Prefer `chapkit mlproject migrate` or `chapkit init`
Expand All @@ -331,3 +378,4 @@ Use [`chapkit init`](cli-scaffolding.md) instead when you want to start a **gree
| An MLproject you want to quickly evaluate | `chapkit mlproject run` |
| An MLproject you want to own as a chapkit project | `chapkit mlproject migrate` |
| Nothing yet | `chapkit init` |
| A chapkit service you also want to run from an MLproject | [`chapkit mlproject export`](mlproject-export.md) |
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ nav:
- MLproject Runner: guides/mlproject-runner.md
- MLproject Migration Checklist: guides/mlproject-migration-checklist.md
- MLproject Migrate: guides/mlproject-migrate.md
- MLproject Export: guides/mlproject-export.md
- Deploying to chap-core: guides/deploying-to-chap-core.md
- Testing ML Services: guides/testing-ml-services.md
- Configuration Management: guides/configuration-management.md
Expand Down
8 changes: 6 additions & 2 deletions src/chapkit/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from chapkit import __version__
from chapkit.cli.artifact import artifact_app
from chapkit.cli.export import export_command
from chapkit.cli.init import init_command
from chapkit.cli.migrate import migrate_command
from chapkit.cli.mlproject import MLPROJECT_FILENAMES
Expand Down Expand Up @@ -105,16 +106,19 @@ def callback(
if _find_chapkit_project() is not None:
app.command(name="test", help="Run end-to-end test of the ML service workflow")(test_command)

# 'run' and 'migrate' operate on MLflow-style MLproject directories - the canonical
# 'run', 'migrate' and 'export' work with MLflow-style MLproject files - the canonical
# surface lives under `chapkit mlproject`, hidden from --help when no MLproject file
# is in the current directory.
mlproject_app = typer.Typer(
name="mlproject",
help="Run or migrate an MLflow-style MLproject directory",
help="Run, migrate or export an MLflow-style MLproject",
no_args_is_help=True,
)
mlproject_app.command(name="run", help="Run an MLproject file or directory as a chapkit service")(run_command)
mlproject_app.command(name="migrate", help="Migrate an MLproject directory into a chapkit project")(migrate_command)
mlproject_app.command(name="export", help="Generate an MLproject from a chapkit service module such as main.py")(
export_command
)
app.add_typer(mlproject_app, name="mlproject", hidden=not _has_mlproject())

# Top-level `chapkit run` / `chapkit migrate` stay registered (hidden) as backwards-
Expand Down
Loading
Loading