A small MLOps tool stack: Git, DVC, MLflow, Optuna, pytest and CI, each answering one question

Most MLOps tool stack guides are lists. Nine kinds of tool, one paragraph each: a language, code versioning, data versioning, experiment tracking, pipelines, compute, unit tests, optimisation, and a training framework. Every paragraph is true, and none of it helps you build anything. A list of tools does not tell you what each one is for, or what goes wrong without it.

So I built one instead. I took one small model and wrapped it in the smallest MLOps tool stack I would trust: Git, DVC, MLflow, Optuna and pytest, with a CI workflow on top. I ran every step, broke it on purpose twice, and kept the output. Here is what each tool actually does for you.


Six questions an MLOps tool stack answers

The easiest way to understand an MLOps tool stack is to start from the questions you cannot answer without one. Six months after you ship a model, someone asks why it made a bad prediction. To answer, you need to know all of these:

QuestionTool in this postWhat it records
Which code trained it?GitThe commit of every script
Which data trained it?DVCA hash of every data file, stored in Git
Which run produced it, and how did it score?MLflowParameters and metrics of every training run
Why these settings?OptunaEvery trial it tried, and the trade-offs between them
Was it good enough to ship?pytestData checks and a quality bar the model had to pass
Who ran all of that, and when?CI (GitHub Actions)The same steps, on every change, the same way

If you cannot answer one of these, that is the tool to add next. The rest of this post builds each layer in order.

Setting up the MLOps tool stack

Everything here runs on a laptop. I used Python 3.12 with these versions, all installed with pip:

pip install scikit-learn==1.9.1 mlflow==3.18.0 optuna==5.1.0 dvc==3.67.1 pandas==3.1.1 pytest==9.2.0

The model is a random forest that classifies tumours as malignant or benign, using the breast cancer dataset that ships with scikit-learn. It is small enough to train in seconds, which keeps the focus on the plumbing rather than the model. If random forests are new to you, my post on ensemble methods explains how they work.

Step 1: version the data with DVC

Git is good at code and bad at data. Data files are large, change in bulk, and do not diff well. DVC solves this by storing a small text file in Git that records a hash of each data file, while the data itself lives in a cache or a remote store such as S3.

First, a script writes the dataset to data/raw.csv. In a real project this would be your export from a database or a data warehouse.

"""Write the raw dataset to data/raw.csv (stands in for your real data export)."""
from pathlib import Path

from sklearn.datasets import load_breast_cancer

Path("data").mkdir(exist_ok=True)
frame = load_breast_cancer(as_frame=True).frame
frame.to_csv("data/raw.csv", index=False)
print(f"wrote data/raw.csv: {len(frame)} rows, {frame.shape[1]} columns")

Then DVC takes over:

$ python prepare.py
wrote data/raw.csv: 569 rows, 31 columns
$ dvc init
$ dvc add data/raw.csv
$ cat data/raw.csv.dvc
outs:
- md5: 5afc23b9622f8f9ffa60824f4e97d0d5
  size: 121385
  hash: md5
  path: raw.csv

That small .dvc file is what you commit. DVC also adds raw.csv to data/.gitignore so the data itself stays out of Git. Now every commit points at an exact version of the data, through its hash.

To see why that matters, I deleted one row from the CSV, the kind of silent change that happens when an export query is edited. DVC noticed straight away:

$ dvc status
data/raw.csv.dvc:
	changed outs:
		modified:           data/raw.csv

Step 2: test the data before you train

DVC tells you the data changed. It does not tell you whether the change is a problem. That is a job for ordinary tests. Mine check the shape, missing values and the label balance:

import pandas as pd

data = pd.read_csv("data/raw.csv")


def test_expected_columns_and_size():
    assert "target" in data.columns
    assert data.shape == (569, 31)


def test_no_missing_values():
    assert not data.isna().any().any()


def test_labels_are_binary_and_not_badly_skewed():
    assert set(data["target"].unique()) == {0, 1}
    assert 0.3 < data["target"].mean() < 0.7

With the row deleted, the first test failed with a clear message:

>       assert data.shape == (569, 31)
E       assert (568, 31) == (569, 31)
FAILED tests/test_data.py::test_expected_columns_and_size

An exact row count is too strict for data that grows every day; in that case, test a range instead. The point is to stop training on data you did not expect, before it costs you an hour of compute and a confusing result.


Step 3: tune for two goals with Optuna, and log it with MLflow

This is the step most tool lists call “multiobjective optimisation” and then do not explain. Most tuning examples chase one number, usually accuracy. Real models have at least two goals that pull against each other. Here I wanted a high ROC AUC and fast predictions, because a bigger forest scores a little better but takes longer to answer.

Optuna can tune for both at once. Each trial trains a forest with different settings, measures both goals, and logs everything to MLflow as its own run:

"""Tune a model on two objectives and log every trial to MLflow."""
import time

import joblib
import mlflow
import optuna
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

SEED = 42
data = pd.read_csv("data/raw.csv")
X, y = data.drop(columns="target"), data["target"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=SEED)

mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("tumour-classifier")


def predict_ms(model):
    """Median time to score the whole test set, in milliseconds."""
    times = []
    for _ in range(5):
        start = time.perf_counter()
        model.predict_proba(X_test)
        times.append((time.perf_counter() - start) * 1000)
    return sorted(times)[2]


def objective(trial):
    params = {
        "n_estimators": trial.suggest_int("n_estimators", 10, 400, log=True),
        "max_depth": trial.suggest_int("max_depth", 2, 16),
        "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
    }
    with mlflow.start_run(nested=True):
        model = RandomForestClassifier(**params, random_state=SEED, n_jobs=1)
        model.fit(X_train, y_train)
        auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
        latency = predict_ms(model)
        mlflow.log_params(params)
        mlflow.log_metrics({"auc": auc, "predict_ms": latency})
    return auc, latency


with mlflow.start_run(run_name="tuning"):
    study = optuna.create_study(
        directions=["maximize", "minimize"],
        sampler=optuna.samplers.NSGAIISampler(seed=SEED))
    optuna.logging.set_verbosity(optuna.logging.WARNING)
    study.optimize(objective, n_trials=40)

    # The Pareto front: no other trial is both more accurate and faster.
    front = sorted(study.best_trials, key=lambda t: t.values[1])
    print("Pareto front (auc, predict_ms, params):")
    for t in front:
        print(f"  {t.values[0]:.4f}  {t.values[1]:6.2f} ms  {t.params}")

    # Pick the fastest model within 0.002 AUC of the best one.
    best_auc = max(t.values[0] for t in front)
    chosen = next(t for t in front if t.values[0] >= best_auc - 0.002)
    print(f"chosen: auc={chosen.values[0]:.4f} "
          f"predict_ms={chosen.values[1]:.2f} {chosen.params}")

    model = RandomForestClassifier(**chosen.params, random_state=SEED, n_jobs=1)
    model.fit(X_train, y_train)
    joblib.dump(model, "model.joblib")
    mlflow.log_params({f"chosen_{k}": v for k, v in chosen.params.items()})
    mlflow.log_metrics({"chosen_auc": chosen.values[0],
                        "chosen_predict_ms": chosen.values[1]})

With two goals there is no single best trial. Optuna returns the Pareto front instead: the trials where you cannot improve one goal without making the other worse. Here is the front from my run:

Pareto front (auc, predict_ms, params):
  0.9906    0.77 ms  {'n_estimators': 10, 'max_depth': 14, 'min_samples_leaf': 8}
  0.9922    0.84 ms  {'n_estimators': 11, 'max_depth': 15, 'min_samples_leaf': 3}
  0.9931    1.06 ms  {'n_estimators': 17, 'max_depth': 15, 'min_samples_leaf': 9}
  0.9939    1.07 ms  {'n_estimators': 15, 'max_depth': 12, 'min_samples_leaf': 8}
  0.9949    2.95 ms  {'n_estimators': 65, 'max_depth': 10, 'min_samples_leaf': 1}
chosen: auc=0.9931 predict_ms=1.06 {'n_estimators': 17, 'max_depth': 15, 'min_samples_leaf': 9}

Look at the last two rows. The most accurate forest has 65 trees and takes 2.95 ms. A forest with 15 trees scores 0.9939, only 0.001 lower, and is almost three times faster. Single-objective tuning would have handed you the 65-tree model without showing you that choice. My script picks the fastest model within 0.002 AUC of the best, but the rule is yours to set; what matters is that the trade-off is visible and written down in code.

A single best score hides the trade-off. A Pareto front shows it to you.

A note on these timings: they are from one run on my machine, and prediction times this small are noisy. The ranking is what to trust, not the third decimal place.

Step 4: find any run again with MLflow

Every trial became an MLflow run with its parameters and metrics. That is what lets you answer “which run produced this model?” months later. You can browse the runs with mlflow ui, or query them from Python:

import mlflow

mlflow.set_tracking_uri("sqlite:///mlflow.db")
runs = mlflow.search_runs(experiment_names=["tumour-classifier"],
                          order_by=["metrics.auc DESC"])
print(len(runs), "runs logged")
41 runs logged
 metrics.auc  metrics.predict_ms params.n_estimators params.max_depth
    0.994864            2.946709                  65               10
    0.994864            6.058250                 145               13
    0.994864            3.910334                  89               15

Forty-one runs: one parent run for the tuning session and forty trials inside it. Notice the top three rows. Three different forests reached the same AUC, and the slowest took twice as long as the fastest. Without a record like this, you would never know the cheaper model existed.

Step 5: a quality gate the model must pass

The last check is the one that stops a bad model from shipping. It is just another pytest file, run after training:

import joblib
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

data = pd.read_csv("data/raw.csv")
X, y = data.drop(columns="target"), data["target"]
_, X_test, _, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
model = joblib.load("model.joblib")


def test_model_meets_quality_bar():
    auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
    assert auc >= 0.97, f"AUC {auc:.4f} is below the 0.97 release bar"


def test_model_handles_a_single_row():
    assert model.predict(X_test.iloc[[0]]).shape == (1,)

The tuned model passed both tests. Then I saved a deliberately weak model, a decision tree with a single split, over model.joblib and ran the gate again:

E       AssertionError: AUC 0.9079 is below the 0.97 release bar
FAILED tests/test_model.py::test_model_meets_quality_bar

An AUC of 0.91 sounds fine on its own. Against the bar the team agreed, it is a clear no. Writing the bar into a test turns an opinion into a rule that a tired person at 6 p.m. cannot skip.

Step 6: let CI run the whole stack every time

The last layer is automation. The same steps should run on every pull request, the same way, without anyone remembering them. In GitHub Actions that is a short workflow:

name: model
on: [pull_request]

jobs:
  train-and-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - run: dvc pull                  # fetch the exact data version
      - run: pytest tests/test_data.py
      - run: python train.py
      - run: pytest tests/test_model.py

dvc pull only works once the repository has a DVC remote to pull from, such as an S3 bucket or a shared drive. Add one with dvc remote add -d storage s3://your-bucket/dvc, run dvc push once, and give the CI runner read access through a repository secret. Once the tests pass, the workflow can go on to save the model and its MLflow run somewhere your serving system can reach.


What this MLOps tool stack leaves out, and when you need it

This MLOps tool stack is deliberately small. Here is what bigger teams add, and the moment each one starts to pay for itself.

A model registry. MLflow has one built in. Add it when more than one person needs to know which model version is in production right now.

A pipeline tool such as Airflow, Prefect or Dagster. Add it when training depends on several data jobs that must run in order on a schedule, not just when someone opens a pull request.

Serving and monitoring. Add them when the model answers live requests. The tests in this post check the model before release; monitoring checks the data it sees after release, which drifts in ways no test can predict. My post on the bias-variance trade-off covers why a model that tested well can still go wrong on new data.

GPUs and cloud compute. Add them when a training run stops fitting on one machine in a reasonable time. For a model like this one, they would only add cost.

The takeaway

An MLOps tool stack is not a shopping list. Each tool answers one question about a model you have shipped: which code, which data, which run, why these settings, was it good enough, and who ran it. Start with the questions you cannot answer today, add the tool for that, and run it on a real model before you add the next one.

The whole project in this post is a handful of short files and a few minutes of setup. That is a better start than any diagram of fifty logos.

Further reading

Leave A comment

Are you human? Please solve:Captcha