Skip to content

Pipeline of tasks

Train a small image classifier on MNIST with four learning rates at once, evaluate each result, and pick the best one. Every step is an ns.Task, and the same pipeline runs as plain Python or as a Prefect flow.

View example files ↗ · Related reference: Tasks →

flowchart LR
    prepare["prepare<br>CPU"] --> t1["train lr=0.3<br>spot H100"] & t2["train lr=0.1"] & t3["train lr=0.03"] & t4["train lr=0.01"]
    t1 --> e1["evaluate"]
    t2 --> e2["evaluate"]
    t3 --> e3["evaluate"]
    t4 --> e4["evaluate"]
    e1 & e2 & e3 & e4 --> aggregate["aggregate<br>CPU"]

The code is in examples/tasks/mnist/:

File What it holds
tasks.py The image and the five tasks.
train.py The pipeline and the command line: plain Python, or a Prefect flow.
lib/ An ordinary Python package: data loading, the model, training, evaluation. Tasks send it to their jobs with local_libs=["lib"].

Run it

From examples/tasks/mnist/, with Object Storage credentials set:

python train.py

The script starts every job, waits, and prints the best run. No orchestrator is needed.

export PREFECT_API_URL=https://prefect.example.com/api
python train.py --mode prefect-local

pipeline runs as the Prefect flow mnist-baseline in this process. Needs pip install "nebius-serverless[prefect]".

export PREFECT_API_URL=https://prefect.example.com/api
python train.py --mode prefect-remote

pipeline runs as a Prefect flow on a small CPU job. The script prints the link to the flow run and ends once the flow job has started. Prefect is not needed here.

How it fits together

One image. tasks.py builds the training image from an inline Dockerfile with ns.Image(dockerfile_string=...). It is built on the first run and reused after that. aggregate needs only Python and uses python:3.12-slim-bookworm.

Three kinds of task.

  • gpu_check is a bash script. It reads ${inputs[fields]} and sets outputs[gpu_name] and others.
  • prepare wraps prepare_data from the lib package. The job imports it by name.
  • train and evaluate wrap small functions defined in tasks.py that import from lib inside their bodies. aggregate is a self-contained function.

Runs as arguments. train.submit(...) returns at once, so the four training jobs start together. Each run is passed to evaluate.submit(trained=run, ...), whose job starts as soon as that training run has finished. aggregate gets all runs and all scores.

Files. A task writes checkpoints to $NS_OUTPUT_DIR and returns the path. Every task's job sees the task bucket at the same path, so evaluate opens the checkpoint that train wrote.

Spot and preemption. train runs on spot H100 (pricing="spot"). A preempted training job ends in ERROR, and its run raises TaskFailed: run the pipeline again. See Pricing, restarts and preemption.

Prefect. In the Prefect modes, train.py passes the same pipeline to PrefectFlow, which turns each task call into a Prefect task run with a link to its job. A run's files go to flows/mnist-baseline/<run>/ in the bucket, one folder per task job.

Source

tasks.py
"""The tasks and constants of the MNIST baseline experiment.

``train.py`` imports them from here. Run it from this folder: the tasks
send the local package ``lib`` with ``local_libs=["lib"]``, which is
found the same way ``import lib`` finds it.

The training tasks share one image, built from ``DOCKERFILE`` on the
first run and reused after that. ``aggregate`` needs only Python and
uses a public image.

- ``gpu_check``: a bash script, on a GPU job.
- ``prepare``: downloads the dataset, on a CPU job.
- ``train``: trains with one learning rate, on a spot GPU job.
- ``evaluate``: measures one checkpoint, on a GPU job.
- ``aggregate``: puts the runs together and picks the best one, on a
  CPU job. Its result is the experiment's result.
"""

import os

from lib.data.mnist import prepare_data

import nebius_serverless as ns

EXPERIMENT = "mnist-baseline"
LEARNING_RATES = [0.3, 0.1, 0.03, 0.01]

# The API address of the Prefect server, such as
# https://prefect.example.com/api. It is read from the environment, so
# that no server address is kept in this file.
PREFECT_API_URL = os.environ.get("PREFECT_API_URL")

DOCKERFILE = """
FROM python:3.12-slim-bookworm
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
RUN uv pip install --system --compile-bytecode torch==2.8.0 torchvision==0.23.0
"""

image_torch = ns.Image(dockerfile_string=DOCKERFILE)

# A bash script. Its inputs arrive in the bash array ``inputs``; what it
# sets in ``outputs`` comes back as a dict of strings.
gpu_check = ns.Task(
    name="gpu-check",
    image=image_torch,
    gpu="h100",
    timeout="10m",
    inputs=["fields"],
    command="""
    nvidia-smi
    outputs[gpu_count]=$(nvidia-smi --list-gpus | wc -l)
    outputs[gpu_name]=$(
        nvidia-smi --query-gpu=name --format=csv,noheader | head -n 1
    )
    outputs[details]=$(
        nvidia-smi --query-gpu="${inputs[fields]}" --format=csv,noheader \\
            | head -n 1
    )
    """,
)

# A function from the package ``lib``: the job imports it by name.
prepare = ns.Task(
    prepare_data,
    name="prepare-data",
    image=image_torch,
    local_libs=["lib"],
    timeout="30m",
)


def train_step(
    exp_name: str, data_dir: str, lr: float, epochs: int
) -> dict[str, object]:
    """Train the baseline model with one learning rate."""
    from lib.training.baseline import train_baseline

    return train_baseline(
        exp_name=exp_name, data_dir=data_dir, lr=lr, epochs=epochs
    )


# A function defined here: its source is sent, so it imports from ``lib``
# inside its body.
train = ns.Task(
    train_step,
    name="train-baseline",
    image=image_torch,
    local_libs=["lib"],
    gpu="h100",
    pricing="spot",
    timeout="2h",
)


def evaluate_step(
    trained: dict[str, object], data_dir: str
) -> dict[str, object]:
    from lib.evaluation.accuracy import evaluate

    return evaluate(checkpoint=trained["checkpoint"], data_dir=data_dir)


evaluate = ns.Task(
    evaluate_step,
    name="evaluate",
    image=image_torch,
    local_libs=["lib"],
    gpu="h100",
    timeout="30m",
)


def aggregate_results(
    trained: list[dict[str, object]], scores: list[dict[str, object]]
) -> dict[str, object]:
    runs = list(zip(trained, scores))
    for run, score in runs:
        print(
            f"lr {run['lr']}: loss {run['loss']:.3f}, "
            f"accuracy {score['accuracy']:.3f}"
        )
    best, score = max(runs, key=lambda pair: pair[1]["accuracy"])
    return {
        "lr": best["lr"],
        "accuracy": score["accuracy"],
        "checkpoint": best["checkpoint"],
        "accuracy_by_lr": {
            str(run["lr"]): score["accuracy"] for run, score in runs
        },
    }


# A self-contained function on a public image and the smallest CPU machine.
aggregate = ns.Task(
    aggregate_results,
    name="aggregate-results",
    image="python:3.12-slim-bookworm",
    timeout="10m",
)
train.py
"""A baseline experiment as a pipeline of tasks.

Uses ``ns.Task`` and the Prefect integration's ``PrefectFlow``. The
tasks and constants are in ``tasks.py``. The walkthrough is the
"Pipeline of tasks" page of the documentation,
``docs/training/task-pipeline.md``.

The pipeline trains a small image classifier on MNIST with several
learning rates, evaluates each result, and returns the best one:

1. ``gpu_check``: a shell command. Nothing waits for it.
2. ``prepare``: downloads the dataset once, on a CPU job.
3. ``train``: one spot GPU job per learning rate, all at the same time.
4. ``evaluate``: one GPU job per training run, each started as soon as
   its training run has ended.
5. ``aggregate``: picks the best run, on a CPU job.

A path returned by one task is passed to the next one as is. This
relies on every task's job seeing the managed bucket at the same path.

Run it from this folder, in one of three ways::

    python train.py                        # plain Python on this machine
    python train.py --mode prefect-local   # a Prefect flow on this machine
    python train.py --mode prefect-remote  # a Prefect flow on a Nebius job

- ``local`` needs no Prefect. The script waits for the result. Each
  task's files go to ``tasks/<task>/<time>/`` in the managed bucket.
- ``prefect-local`` runs ``pipeline`` as the Prefect flow
  ``mnist-baseline`` in this process (``remote_job=False``). It needs
  Prefect here, ``pip install "nebius-serverless[prefect]"``, and waits
  for the result.
- ``prefect-remote`` sends ``pipeline`` to an on-demand CPU job and
  runs it there as that flow. The script ends once the job has
  started, and the flow keeps running. Prefect is not needed here.

In both Prefect modes:

- The run is recorded on the Prefect server whose API address is in
  ``PREFECT_API_URL``, such as ``https://prefect.example.com/api``.
  Set it before running. If that server asks for a login, also set
  ``PREFECT_API_AUTH_STRING`` to ``user:password``, or put it on one
  line in ``~/.config/prefect/auth``.
- A run is named by its launch time, for example
  ``20261125-091833-mnist-baseline``. Its files go to
  ``flows/mnist-baseline/<run>/`` in the bucket, one folder per task
  job.
- The link to the flow run in the Prefect UI is printed at the start.
  It is the API address without ``/api``; set ``PREFECT_UI_URL`` when
  the UI is elsewhere.
- Each task call is a Prefect task run and one Nebius job, with the
  artifacts ``nebius-job``, ``inputs`` and ``outputs``. Set
  ``NS_CONSOLE_JOB_URL`` to the console address of a job, with
  ``{project}`` and ``{job}`` in it, to get a link to the job in
  ``nebius-job``.

Every run does every step, including the dataset download.
"""

import argparse

from tasks import (
    EXPERIMENT,
    LEARNING_RATES,
    PREFECT_API_URL,
    aggregate,
    evaluate,
    gpu_check,
    prepare,
    train,
)

from nebius_serverless.integrations.prefect import PrefectFlow

MODES = ("local", "prefect-local", "prefect-remote")


def pipeline(epochs: int = 5) -> dict[str, object]:
    """Train with each learning rate, evaluate, and return the best run.

    With Prefect, this function's source is what runs as the flow. From
    outside its body it uses only tasks and constants with JSON values.
    """

    # Nothing waits for it. Calling gpu_check(...) instead would.
    gpu_check.submit(fields="memory.total,driver_version")

    data = prepare.submit(dataset="mnist")
    data_dir = data.result()["data_dir"]

    # One job per learning rate, all at the same time.
    training = [
        train.submit(
            exp_name=EXPERIMENT, data_dir=data_dir, lr=lr, epochs=epochs
        )
        for lr in LEARNING_RATES
    ]

    evaluation = [
        evaluate.submit(trained=run, data_dir=data_dir) for run in training
    ]

    best = aggregate.submit(trained=training, scores=evaluation)
    return best.result()


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Run the MNIST baseline pipeline."
    )
    parser.add_argument(
        "--mode",
        choices=MODES,
        default="local",
        help=(
            "local: plain Python here; prefect-local: a Prefect flow "
            "here; prefect-remote: a Prefect flow on a Nebius job "
            "(default: %(default)s)"
        ),
    )
    mode = parser.parse_args().mode

    if mode == "local":
        result = pipeline()
        print(result)
        return

    flow = PrefectFlow(
        pipeline,
        flow_name=EXPERIMENT,
        api_url=PREFECT_API_URL,
        remote_job=(mode == "prefect-remote"),
        timeout="3h",  # The flow job's limit. Not used by prefect-local.
    )
    run = flow.submit()
    if run.flow_run_url:
        print(f"Prefect: {run.flow_run_url}")


if __name__ == "__main__":
    main()