Metadata-Version: 2.5
Name: cortexgrid
Version: 0.3.22
Summary: Connect your ML code to the RoboLab compute cluster — Ray, MLflow, and S3
Project-URL: Homepage, https://github.com/robodatalab/cortexgrid
Project-URL: Repository, https://github.com/robodatalab/cortexgrid
Project-URL: Documentation, https://github.com/robodatalab/cortexgrid/blob/main/docs/cortexgrid.md
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: <3.12,>=3.11
Requires-Dist: boto3>=1.34
Requires-Dist: cloudpickle>=3.0
Requires-Dist: fabric>=3.2.3
Requires-Dist: fastapi<1,>=0.115
Requires-Dist: haikunator>=2.1.0
Requires-Dist: httpx>=0.27
Requires-Dist: mlflow<4,>=3.11
Requires-Dist: packaging>=24
Requires-Dist: pip>=23.0
Requires-Dist: pydantic-settings>=2.13.1
Requires-Dist: pydantic>=2.13.3
Requires-Dist: pydotenv>=0.0.7
Requires-Dist: python-dotenv>=1.2.2
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: ray[default,serve]<3,>=2.58
Requires-Dist: requests>=2.31
Requires-Dist: setuptools>=82.0.1
Requires-Dist: tqdm>=4.60
Description-Content-Type: text/markdown

[Home](https://github.com/robodatalab/cortexgrid/blob/main/README.md) · **Using cortexgrid** · [Deploying](https://github.com/robodatalab/cortexgrid/blob/main/docs/deployment.md) · Design: [Overview](https://github.com/robodatalab/cortexgrid/blob/main/docs/design/overview.md) · [Jobs](https://github.com/robodatalab/cortexgrid/blob/main/docs/design/jobs.md) · [Model serving](https://github.com/robodatalab/cortexgrid/blob/main/docs/design/model-serving.md) · [Experiment lifecycle](https://github.com/robodatalab/cortexgrid/blob/main/docs/design/experiment_lifecycle.md) · [CI/CD](https://github.com/robodatalab/cortexgrid/blob/main/docs/design/ci-cd.md)

# cortexgrid

`cortexgrid` is a Python library that connects your ML code to a cortexgrid cluster. It wraps Ray, MLflow and S3/MinIO so your scripts don't need to know about URLs, credentials or service endpoints: you track experiments, run functions on the cluster's GPUs, checkpoint them, store files and serve models, all from plain Python.

## Setup

Add `cortexgrid` as a dependency in your project's `pyproject.toml`:

```toml
[project]
dependencies = [
    "cortexgrid",
]
```

Then `uv sync` to install it, and point it at the cluster head's secrets server, reachable over the tailnet:

```bash
export CORTEXGRID_HEAD_URL=http://robolab-head:7700
```

That is the only configuration. Every service URL and credential is read from the head on first use.

The cluster's web UIs, also reachable over the tailnet:

| UI | URL |
|---|---|
| cortexgrid dashboard (experiments, runs, jobs, models, deployments) | https://cortexgrid.robodatalab.com |
| MLflow (metrics and params) | https://mlflow.robodatalab.com |
| Ray dashboard (jobs, Serve apps, logs) | https://ray.robodatalab.com |

## Experiments and runs

Everything you do is recorded against a run, and every run belongs to an experiment. Start one at the top of your script:

```python
import cortexgrid

cortexgrid.Experiment.init("weather-forecast")
```

That creates the experiment if it does not exist yet and starts a new run inside it. Omit the name to get a generated one like `funky-koval-12`. Each run gets a generated name too, which `cortexgrid.Experiment.get_instance().run_name()` returns.

There is one active run per process. Calling `Experiment.init` again with the same name, or with none, returns the active run; calling it with a different name raises `ValueError`. `Experiment.close()` detaches the active run so another can be started. `Experiment.from_experiment(experiment_name, run_id)` attaches to an existing run instead of starting one, which is what jobs on the cluster do.

```python
cortexgrid.list_experiments()                  # every run, as (experiment_name, run_id)
cortexgrid.delete_run(run_id)                  # stops its jobs, deletes its files, models and records
cortexgrid.delete_experiment("weather-forecast")   # deletes every run, then the experiment
```

## Tracking metrics and params

```python
cortexgrid.Experiment.init("weather-forecast")

cortexgrid.log_params({"lr": 1e-3, "epochs": 20, "batch_size": 64})

for epoch in range(20):
    loss = train_one_epoch(model, dataloader)
    cortexgrid.log_metric("loss", loss, step=epoch)

cortexgrid.log_artifact("plots/loss.png", artifact_path="plots")
```

Everything is logged to the active run's MLflow run, and shows up in MLflow. Jobs submitted with `cortexgrid.remote` log to the same run as the script that submitted them.

To read it back:

```python
cortexgrid.list_run_metrics(run_id)            # metric names
cortexgrid.get_metric_history(run_id, "loss")  # every logged value
cortexgrid.list_run_params(run_id)
cortexgrid.list_run_artifacts(run_id)
cortexgrid.get_mlflow_client()                 # raw mlflow.tracking.MlflowClient
```

## Running code on the cluster

### Submitting a job

```python
def train_step(batch):
    # runs on a cluster GPU
    return loss

job = cortexgrid.remote(train_step, batch, num_gpus=1, retry=True)
print(f"Submitted: {job.job_id}")
```

`cortexgrid.remote(fn, *args, num_gpus=0, num_cpus=1, retry=False, **kwargs)` submits a function and its arguments to the cluster and returns a `JobFuture` at once. It needs no decorator, Dockerfile or commit: cortexgrid ships the code the function needs with it.

- **Your own modules** ship as source: everything the function's file imports, transitively, that is not installed in site-packages.
- **Third-party packages** are installed on the worker at the versions installed locally (`tqdm==4.67.3`). Packages the worker image already has (torch and its CUDA stack, ray, mlflow, ...) are not installed again.
- **The standard library** is not shipped.

An import of a file in site-packages that no installed distribution owns makes `remote` raise `UnownedDependencyError`.

Follow a job with `job.status()` (a `JobStatus`), `job.done()`, the cortexgrid dashboard, or `cortexgrid.list_experiment_run_jobs(run_id)`.

### Waiting for the result

`JobFuture.result(timeout=None)` blocks until the job finishes, then behaves like a local call: it returns what the function returned, or raises what it raised.

```python
def score(batch) -> dict[str, float]:
    return {"loss": 0.12}

job = cortexgrid.remote(score, batch, num_gpus=1)
metrics = job.result()                   # {"loss": 0.12}
metrics = job.result(timeout=600)        # TimeoutError if not done; the job keeps running

metrics = cortexgrid.get_job_result(job_id, timeout=600)   # from another process of the same run
```

Failures arrive as exceptions:

```python
try:
    metrics = job.result()
except BadBatch as exc:                # exactly what score() raised on the cluster
    print(exc.__cause__)               # JobFailed, carrying the remote traceback
except cortexgrid.JobFailed:           # the job never got as far as returning
    ...                                # submission failed, driver died, or stopped
except cortexgrid.JobResultUnavailable:
    ...                                # it returned, but the value could not be pickled
```

| Outcome | What `result()` does |
|---|---|
| The function returned | Returns its value |
| The function raised | Raises that exception, with a `JobFailed` carrying the remote traceback as its cause |
| The job never got as far as returning (submission failed, driver died, job stopped) | Raises `JobFailed` |
| The value or the exception did not survive cloudpickle | Raises `JobResultUnavailable` (value) or `JobFailed` (exception). The job itself does not fail |
| `timeout` elapsed | Raises `TimeoutError`; the job keeps running |

### Retries

With `retry=True`, the cluster resubmits the job every time it fails. Retries are unbounded on purpose: you end a retry loop by stopping the job. Because of that, `result()` on a `retry=True` job raises `ValueError` instead of waiting forever. Use [checkpoints](#checkpointing) so a retry continues where the failed attempt stopped.

### Stopping jobs

```python
cortexgrid.stop_experiment_run_jobs(run_id)   # stops every job in the run
```

Jobs can also be stopped from the cortexgrid dashboard. A stopped job that was never started is never started.

## Checkpointing

Inside a job, `cortexgrid.checkpoint()` returns a checkpoint you set attributes on; it is saved when its `with` block exits without an error. When the job is retried, `cortexgrid.resume()` returns the job's last checkpoint, or `None` if it has none.

```python
def train(dataloader):
    ckpt = cortexgrid.resume()
    if ckpt:
        ckpt.restore_training_state(model, optimizer)
        start_epoch = ckpt.epoch + 1
    else:
        start_epoch = 0

    for epoch in range(start_epoch, 20):
        train_one_epoch(model, dataloader)
        with cortexgrid.checkpoint() as ckpt:
            ckpt.epoch = epoch
            ckpt.save_training_state(model, optimizer)

cortexgrid.remote(train, dataloader, num_gpus=1, retry=True)
```

An attribute can hold any cloudpickle-compatible value (`ckpt.metric = 0.93`, `ckpt.weights = model.state_dict()`). `save_training_state(model, optimizer, scheduler=None)` and `restore_training_state(...)` are shortcuts for the state dicts of a model, its optimizer and optionally its scheduler. Each new checkpoint replaces the previous one. Outside a job, all processes of the run share one checkpoint.

## Object storage

The cluster has one bucket: S3 on AWS, MinIO on-prem. The same calls work on both.

```python
cortexgrid.upload("data/output.parquet", dest_path="run-42/output.parquet")   # returns the s3:// URI
cortexgrid.upload_dir("data/shards", dest_path="run-42/shards")              # every file in the tree
cortexgrid.download("run-42/output.parquet", local_path="./output.parquet")
cortexgrid.delete_prefix("run-42/")

s3 = cortexgrid.get_s3_client()   # raw boto3 client
```

## Secrets

Secrets live on the cluster head and are readable from your machine and from jobs and serve-apps on the cluster alike:

```python
cortexgrid.set_secret("ANTHROPIC_API_KEY", "sk-ant-...")
key = cortexgrid.get_secret("ANTHROPIC_API_KEY")
cortexgrid.list_secrets()
cortexgrid.delete_secret("ANTHROPIC_API_KEY")
```

Anyone on the tailnet can read them, so the tailnet is the boundary.

## Serving models

Serving a model takes three steps: write a **serve-app** (the class that answers requests), **register** the model, and **deploy** it. A registered model is identified by `(family, suffix, run_name)`, and that triple is all anyone needs to deploy it later, from any script.

For ready-made serve-apps and importers (HuggingFace models, Anthropic, Gemini), see [cortexgrid-infer](https://github.com/robodatalab/cortexgrid-infer): it supplies the arguments of the calls below, so you can skip step 1.

### 1. Write a serve-app

A serve-app is a class marked with cortexgrid's `serve.ingress` (not Ray's). Its constructor receives the `DeploymentKey` it serves, its `serve.endpoint` methods become its HTTP routes, and cortexgrid generates a client with the same methods. Put it in its own module, not in the script you run: cortexgrid imports it by module path on the cluster, and `__main__` does not import there.

```python
# models.py
import json

import cortexgrid
from cortexgrid import serve

@serve.ingress
class Linear:
    def __init__(self, deployment: cortexgrid.DeploymentKey) -> None:
        weights_dir = cortexgrid.load_model(
            deployment.family, deployment.suffix, deployment.run_name
        )
        weights = json.loads((weights_dir / "weights.json").read_text())
        self._slope = weights["slope"]

    @serve.endpoint
    def predict(self, xs: list[float]) -> list[float]:
        return [self._slope * x for x in xs]
```

Each endpoint answers POST `/<method name>`, with its arguments and answer converted to and from JSON by their type annotations, so dataclasses and pydantic models work as they are. An endpoint may be a `def`, an `async def`, or an async generator, which streams what it yields. The client's methods mirror them: a `def` endpoint's returns the value, an `async def` endpoint's returns a coroutine, and an async generator's yields the answers as they arrive.

### 2. Register the model

Pick the call that matches where the weights come from:

| Weights | Call | `run_name` |
|---|---|---|
| Produced by this run (e.g. a fine-tune) | `cortexgrid.save_model(weights_dir, Linear, family, suffix)` | The current run's; every run saves a new copy |
| Produced elsewhere (e.g. a pretrained base model) | `cortexgrid.import_model(source, Linear, family, suffix)` | `cortexgrid.IMPORTED`; uploaded once, reused on later calls |
| None (the serve-app forwards to a hosted API) | `cortexgrid.register_model(Linear, family, suffix)` | `cortexgrid.IMPORTED`; registered once, reused on later calls |

All three need an active run, return a `SavedModel` carrying the `run_name` to deploy, and take optional `requirements=` and `config=` (see [Hardware requirements](#hardware-requirements) and [Model config](#model-config)). `import_model`'s `source` can be a directory or a function returning one, which then runs only when an upload actually happens. `import_model` and `register_model` re-bundle the serve-app when its code has changed, so it is safe to call them at the top of every script.

```python
import cortexgrid
from models import Linear

cortexgrid.Experiment.init("my-experiment")
saved = cortexgrid.save_model(
    weights_dir, Linear, family="examples", suffix="linear",
    requirements=cortexgrid.ModelRequirements(num_gpus=1, ram_gb=8, vram_gb=16),
)
```

### 3. Deploy and call it

```python
deployed = cortexgrid.deploy_model(saved.family, saved.suffix, saved.run_name)
model: Linear = deployed.client()   # blocks until the app is serving
print(model.predict([1.0, 2.0]))
```

`deploy_model` schedules the app and returns a `Deployment` (`key`, `url`, `phase`). With `wait=True` it blocks until the app serves, raising `cortexgrid.ModelDeployFailed` if it fails and `TimeoutError` after `timeout` seconds (300 by default). `num_replicas=` sets how many copies run.

- `deployed.client()` waits for the app to serve, then returns the client; `deployed.client_async()` returns it at once, and `await client.is_ready()` tells whether the app serves yet.
- Deploying a model that is already live with the same arguments changes nothing. Re-deploying a failed one retries it from scratch.
- `cortexgrid.wait_for_model_serving(key, timeout=...)` waits on a deploy started elsewhere.

### 4. Undeploy and delete

```python
cortexgrid.undeploy_model(deployed.key)
cortexgrid.delete_model(saved.family, saved.suffix, saved.run_name)
```

Undeploying leaves the model registered and deployable. Deleting removes its weights and code, but does not undeploy it.

### Hardware requirements

`ModelRequirements(num_gpus, ram_gb, vram_gb, models)` is what one replica needs, in GiB, with 0 meaning no requirement. It is stored with the model, not with the serve-app class, and a replica is placed only on a node that has it free.

- Among the GPUs that fit, a replica goes to the **smallest**, so a 4 GiB model does not occupy a 128 GiB card a bigger model needs.
- `num_gpus` can be a fraction (`0.25`) to share one card between models; `vram_gb` is what keeps them from overcommitting it.
- A model with no requirements can be placed on any node, CPU-only ones included.

Change them with `cortexgrid.set_model_requirements(family, suffix, run_name, requirements)` or on the model card in the dashboard; it takes effect on the next deploy. `import_model` stores requirements only when it uploads the model or finds none stored, so an edit is not overwritten by the next run that imports it.

### Model config

Anything else the serve-app has to know about the model (which model a provider should be asked for, an endpoint, the name of a secret to read) goes in a `dict[str, str]` stored with it. The serve-app reads it in `__init__`:

```python
cortexgrid.register_model(
    AnthropicServeApp, family="anthropic", suffix="opus",
    config={"model": "claude-opus-5", "api_key_secret": "ANTHROPIC_API_KEY"},
)

@serve.ingress
class AnthropicServeApp:
    def __init__(self, deployment: cortexgrid.DeploymentKey) -> None:
        config = cortexgrid.model_config(deployment)
        self._model = config["model"]
        self._key = cortexgrid.get_secret(config["api_key_secret"])
```

Keys and values must be strings. Anyone with registry access can read the config, so put credentials in [secrets](#secrets) and only their names in the config. `cortexgrid.set_model_config(family, suffix, run_name, config)` or the model card replaces the whole mapping; a running replica keeps the values it started with until it is redeployed.

### Deployment config

How one deployment serves a model (thinking on or off, a context length) belongs to that deployment, and is passed to `deploy_model`:

```python
thinking = cortexgrid.deploy_model("qwen3", "8b", cortexgrid.IMPORTED, config={"thinking": "true"})
direct = cortexgrid.deploy_model("qwen3", "8b", cortexgrid.IMPORTED, config={"thinking": "false"})
```

Each distinct config is its own deployment, with its own `DeploymentKey` and URL, and the same config always lands on the same one. `model_config(deployment)` returns the model's config with the deployment's laid over it.

### Models that use other models

A serve-app that calls another model declares it as a `cortexgrid.DeploymentConfig` in its requirements. Registering the outer model registers the dependency too: with `import_model` when `source` is given, with `register_model` when only `serve_app` is, and not at all when neither is, for a model registered elsewhere. Deploying the outer model deploys the dependency first, with the `DeploymentConfig`'s `num_replicas` and `config`. Inside, `cortexgrid.required_models(deployment)` returns the dependencies' `Deployment`s in the declared order.

```python
@serve.ingress
class SquareRooted:
    def __init__(self, deployment: cortexgrid.DeploymentKey) -> None:
        linear = cortexgrid.required_models(deployment)[0]
        self._linear: Linear = linear.client()

    @serve.endpoint
    def predict(self, xs: list[float]) -> list[float]:
        return [math.sqrt(y) for y in self._linear.predict(xs)]

cortexgrid.register_model(
    SquareRooted, family="examples", suffix="squarerooted",
    requirements=cortexgrid.ModelRequirements(
        models=[
            cortexgrid.DeploymentConfig(
                family="examples", suffix="linear", run_name=cortexgrid.IMPORTED,
                serve_app=Linear, source=linear_weights,
            )
        ],
    ),
)
cortexgrid.deploy_model("examples", "squarerooted", cortexgrid.IMPORTED)
```

The full example is in [cortexgrid_examples/model_dependencies/](https://github.com/robodatalab/cortexgrid/tree/main/cortexgrid_examples/model_dependencies/).

### More models than GPUs

You can deploy more models than the cluster's GPUs hold at once. When a model needs room that idle models hold, the least recently used idle models are paused (scaled to zero replicas) to make it. A request to a paused model waits while the model reloads, which can take minutes for a large one, so give clients a generous timeout. A model that is handling requests is never paused.

### Keeping deployments on the latest code

A deployment keeps running the serve-app code it was deployed with. When the registry holds newer code (after `import_model` re-bundled it, or `save_model` saved again), the dashboard marks the deployment **update**. Deploying it again, `cortexgrid.redeploy_model(key)`, or **Redeploy** on its card moves it to the new code.

### Status

```python
cortexgrid.model_registry_status(family, suffix, run_name)   # SavedModel or None; .phase: uploading / ready / upload_failed / broken
cortexgrid.list_models()                                     # every registered model

cortexgrid.model_serving_status(deployed.key)                # ServingStatus: .phase, .message, .url
cortexgrid.list_deployed_models()                            # every deployment
```

A deployment's `phase` is `not_deployed`, `not_started`, `deploying`, `running`, `paused`, `unhealthy`, `deleting` or `failed`; `message` says why it failed. `deploying` covers downloading the weights and running the serve-app's `__init__`, which can take minutes. Each deployment also shows in the Ray dashboard under Serve.

| Symptom | Cause | Fix |
|---|---|---|
| `save_model` raises; the model is left `upload_failed` | Storage unreachable, or the serve-app (or something it imports) cannot be imported | Fix the cause, `delete_model` the failed entry, save again |
| `save_model` raises `ValueError: ... is wrapped by ray.serve.ingress` | The serve-app uses Ray's `serve.ingress` | Use `from cortexgrid import serve` instead |
| The model reads `broken` | The process saving it died mid-upload | `delete_model` it and save again |
| `deploy_model` raises `ValueError: No saved model for ...` | Wrong triple, or the save is still `uploading` | Check `model_registry_status` |
| `ModelDeployFailed: ... DEPLOY_FAILED: <message>` | The replica failed to install its dependencies or construct the serve-app | Read the message and the replica logs in the Ray dashboard; fix, save again, redeploy |
| `TimeoutError` while deploying | No node has the requirements free, and pausing idle models cannot make room | Check the requirements against the cluster; free GPUs |
| `ModelDeployFailed: ... does not exist` | The app was undeployed, or dropped by a concurrent deploy | Deploy again |

## API reference

Everything is imported from `cortexgrid`.

### Experiments

| Function | Description |
|---|---|
| `Experiment.init(name=None)` | Start a new run in the named experiment, creating it if needed. One active run per process |
| `Experiment.from_experiment(experiment_name, run_id)` | Attach to an existing run |
| `Experiment.get_instance()` / `.close()` | The active run; detach it |
| `Experiment.run_name()` | The active run's name |
| `list_experiments()` | Every run, as `Experiment(experiment_name, run_id)` |
| `delete_run(run_id)` / `delete_experiment(name)` | Delete a run, or an experiment with all its runs |

### Tracking

| Function | Description |
|---|---|
| `log_metric(key, value, step=None)` / `log_metrics(metrics, step=None)` | Log one or several metrics |
| `log_params(params)` | Log parameters |
| `log_artifact(local_path, artifact_path=None)` | Log a file as an artifact |
| `list_run_metrics(run_id)` / `get_metric_history(run_id, key, max_points=None)` | Read metrics back |
| `list_run_params(run_id)` / `list_run_artifacts(run_id, path="")` | Read params and artifacts back |
| `get_mlflow_client()` | Raw MLflow client |

### Jobs

| Function | Description |
|---|---|
| `remote(fn, *args, num_gpus=0, num_cpus=1, retry=False, **kwargs)` | Submit a function to the cluster; returns a `JobFuture` |
| `JobFuture.status()` / `.done()` / `.result(timeout=None)` | A job's status, whether it finished, and its function's result |
| `get_job_result(job_id, timeout=None)` | Wait for a job of the active run by id |
| `list_experiment_run_jobs(run_id)` | Every job of a run, as `JobLifecycle` records |
| `stop_experiment_run_jobs(run_id)` | Stop every job of a run |
| `get_ray_job_id_for_cortexgrid_job(run_id, job_id)` | Ray submission id of a job's latest attempt, or `None` |
| `get_ray_job_status(ray_job_id)` / `get_ray_logs(ray_job_id)` / `get_ray_job_url(ray_job_id)` | A Ray submission's status, logs, and dashboard URL |
| `checkpoint()` / `resume()` | Save the current job's checkpoint; load its last one |

### Storage and secrets

| Function | Description |
|---|---|
| `upload(local_path, dest_path=None)` / `upload_dir(local_dir, dest_path="")` | Upload a file or a directory tree |
| `download(src_path, local_path=None)` | Download a file |
| `delete_prefix(prefix)` | Delete everything under a prefix |
| `get_s3_client()` | Raw boto3 S3 client |
| `get_secret(id)` / `set_secret(id, value)` / `list_secrets()` / `delete_secret(id)` | Cluster secrets |

### Model registry

| Function | Description |
|---|---|
| `save_model(weights_dir, serve_app, family, suffix, requirements=None, config=None)` | Save weights produced by this run |
| `import_model(source, serve_app, family, suffix, requirements=None, config=None)` | Import weights produced elsewhere, once |
| `register_model(serve_app, family, suffix, requirements=None, config=None)` | Register a model with no weights, once |
| `load_model(family, suffix, run_name)` | Download a model's weights; returns the directory |
| `model_config(deployment)` / `set_model_config(family, suffix, run_name, config)` | Read a deployment's config; replace a model's |
| `set_model_requirements(family, suffix, run_name, requirements)` | Replace a model's hardware requirements |
| `model_registry_status(family, suffix, run_name)` / `list_models()` | One model's `SavedModel`, or all of them |
| `delete_model(family, suffix, run_name)` | Delete a model's weights, code and entry |

### Model serving

| Function | Description |
|---|---|
| `serve.ingress` / `serve.endpoint` | Mark a serve-app class and the methods it serves (`from cortexgrid import serve`) |
| `deploy_model(family, suffix, run_name, num_replicas=1, wait=False, timeout=300.0, config=None)` | Deploy a model; returns a `Deployment` |
| `Deployment.client()` / `.client_async()` | The serve-app's client for the deployment |
| `wait_for_model_serving(key, timeout=None)` | Wait until a deployment serves |
| `redeploy_model(key)` | Deploy again with the same config, on the latest code |
| `undeploy_model(key)` | Remove a deployment |
| `required_models(deployment)` | The `Deployment`s of the models a model requires |
| `model_serving_status(key)` / `list_deployed_models()` | One deployment's `ServingStatus`, or all deployments |
