TGraphX › Insights › TGraphX MLflow Integration: Tracking GNN Experiments
← Back to Insights

TGraphX MLflow Integration: Tracking GNN Experiments

Topic: APIs, tooling and research-engineering workflow

Graph experiments have many moving parts: how edges are built, what the node tensor looks like, how graphs are pooled, how the data is split, plus the usual hyperparameters. If those are not recorded with the results, a change in the data can easily be mistaken for a better model.

TGraphX includes a small MLflow adapter, tgraphx.MLflowLogger. It starts an MLflow run and sends it your metrics, including from tgx.fit. Parameters, artifacts and tags are logged with the normal mlflow functions inside the same run. This guide builds a complete tracked graph classification experiment around it: logging, a small sweep, querying, reloading the best model and handling failed runs.

The examples were tested with TGraphX 1.5.1 and MLflow 3.18 (the mlflow-skinny distribution) on CPU, using a local file store. The web UI and the database backend were not part of that test.

An earlier version of this page said TGraphX had no MLflow adapter and used an ExperimentTracker class. Both statements were wrong.

MLflow terms in one minute

  • A run is one execution, with a status, parameters, metrics, tags and artifacts.
  • Parameters are configuration values logged once, stored as strings.
  • Metrics are numbers, optionally logged at many steps.
  • Artifacts are files attached to a run, such as weights or a JSON report.
  • An experiment is a named group of runs.

Installation and where runs are stored

bash
pip install "tgraphx[mlflow]"

The extra installs mlflow>=2.0 next to TGraphX. Where data goes depends on the MLflow version. In the 3.18 release used here, the default is a SQLite database, sqlite:///mlflow.db, unless an ./mlruns folder with earlier data already exists. That release also treats the older file store as being in maintenance mode: it raises an error unless you set MLFLOW_ALLOW_FILE_STORE=true.

For real work, use the database or a tracking server. The code below points at a throwaway file store so that it runs without any database packages; to keep your runs, change TRACKING_URI to "sqlite:///mlflow.db" and drop the environment variable.

Setup and data

The task is graph classification on 300 small synthetic graphs whose two classes differ by a weak shift in the node features. Training, validation and test graphs are separate.

python
import copy
import os
import tempfile
from itertools import product

import mlflow
import torch
import torch.nn as nn

import tgraphx as tgx
from tgraphx import Graph, GraphDataLoader, GraphDataset, MLflowLogger
from tgraphx.reproducibility import reproducibility_report, set_seed

TRACKING_URI = "file:" + os.path.abspath("mlruns_demo")   # tutorial only
os.environ["MLFLOW_ALLOW_FILE_STORE"] = "true"            # MLflow 3.18 needs this for a file store
mlflow.set_tracking_uri(TRACKING_URI)
EXPERIMENT = "tgraphx-graph-classification"

seed_state = set_seed(42)


def make_graph(label, gen):
    n = int(torch.randint(8, 16, (1,), generator=gen))
    x = torch.randn(n, 8, generator=gen) + 0.2 * label          # weak class signal
    edge_index = torch.randint(0, n, (2, 3 * n), generator=gen)
    return Graph(node_features=x, edge_index=edge_index, graph_label=torch.tensor(label))


gen = torch.Generator().manual_seed(0)
graphs = [make_graph(i % 2, gen) for i in range(300)]
train_set, val_set, test_set = graphs[:200], graphs[200:250], graphs[250:]

# one batch each for validation and test, so batch-averaged metrics equal sample averages
val_loader = GraphDataLoader(GraphDataset(val_set), batch_size=len(val_set))
test_loader = GraphDataLoader(GraphDataset(test_set), batch_size=len(test_set))


def make_train_loader():
    return GraphDataLoader(GraphDataset(train_set), batch_size=32, shuffle=True)


def make_model(hidden):
    return tgx.build_model("graph_classification", layer="linear", in_shape=(8,),
                           hidden_shape=(hidden,), num_layers=2, num_classes=2)

The shortest integration: fit(logger=...)

MLflowLogger is a context manager, and tgx.fit accepts it as logger. Each epoch's train_loss, val_loss and any metrics are logged with the epoch number as the MLflow step:

python
model = make_model(32)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

with MLflowLogger(run_name="quick_fit", experiment=EXPERIMENT,
                  tracking_uri=TRACKING_URI) as run:
    mlflow.log_params({"hidden": 32, "lr": 0.01, "epochs": 5})
    tgx.fit(model, make_train_loader(), val_loader, epochs=5, optimizer=optimizer,
            loss_fn=nn.CrossEntropyLoss(), metrics={"acc": tgx.accuracy},
            logger=run, device="cpu")
    quick_run_id = run.run_id

print(sorted(mlflow.get_run(quick_run_id).data.metrics))
# ['train_acc', 'train_loss', 'val_acc', 'val_loss']

Three behaviours to know:

  • fit keeps the weights of the last epoch. It does not select or save a best model.
  • The logger records metrics only. Values that cannot be converted to float are skipped without a message.
  • tracking_uri and experiment change MLflow's global settings for the process, and the logger cannot be opened while another MLflow run is active.

A complete tracked experiment

For an experiment you want to keep, record the configuration, the data, the environment and the best weights, and choose the best epoch on validation data. This function uses train_epoch and evaluate so it can do that:

python
def graph_stats(split):
    return {"num_graphs": len(split),
            "mean_nodes": sum(g.num_nodes for g in split) / len(split),
            "mean_edges": sum(g.num_edges for g in split) / len(split),
            "feature_shape": str(split[0].feature_shape)}


def train_and_log(hidden, lr, epochs=15, seed=42, tags=None):
    set_seed(seed)
    train_loader = make_train_loader()
    model = make_model(hidden)
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    loss_fn = nn.CrossEntropyLoss()
    config = {"layer": "linear", "pooling": "mean", "num_layers": 2, "hidden": hidden,
              "lr": lr, "epochs": epochs, "seed": seed, "batch_size": 32}

    with MLflowLogger(run_name=f"h{hidden}_lr{lr}", experiment=EXPERIMENT,
                      tracking_uri=TRACKING_URI, tags=tags) as run:
        mlflow.log_params(config)
        mlflow.log_params({f"train_data_{k}": v for k, v in graph_stats(train_set).items()})
        mlflow.log_dict(reproducibility_report(), "environment.json")

        best = {"val_loss": float("inf")}
        for epoch in range(epochs):
            train = tgx.train_epoch(model, train_loader, optimizer, loss_fn, device="cpu")
            val = tgx.evaluate(model, val_loader, loss_fn,
                               metrics={"acc": tgx.accuracy}, device="cpu")
            run.log(epoch=epoch, train_loss=train["loss"],
                    val_loss=val["loss"], val_acc=val["acc"])
            if val["loss"] < best["val_loss"]:
                best = {"val_loss": val["loss"], "val_acc": val["acc"], "epoch": epoch,
                        "state": copy.deepcopy(model.state_dict())}

        with tempfile.TemporaryDirectory() as tmp:
            path = os.path.join(tmp, "best_model.pt")
            torch.save(best["state"], path)
            mlflow.log_artifact(path)
        run.log(best_val_loss=best["val_loss"], best_val_acc=best["val_acc"],
                best_epoch=best["epoch"])
        return run.run_id

run.log(epoch=..., name=value) is the usual call; run.log_scalar(tag, value, step) logs a single series. The best epoch is chosen by validation loss: best_val_loss is the lowest loss, and best_val_acc is the validation accuracy at that same epoch, not the highest accuracy the run reached. They are logged as separate metrics because MLflow filters and sorts on a metric's latest value, which for the per-epoch val_acc series is that of the last epoch.

Test graphs are deliberately not touched here. If every run logged a test score, it would be tempting to pick the winner by it.

A small sweep

Each configuration gets its own run, and a tag groups the sweep:

python
for hidden, lr in product((8, 32), (0.003, 0.01)):
    train_and_log(hidden, lr, tags={"sweep": "hidden-lr-v1"})

For a large grid, TGraphX also ships GridRunner for config-driven runs, but it does not log to MLflow and its runner computes no validation loss, so a loop like this one is the better base when selection matters.

Query the runs

python
client = mlflow.MlflowClient()
experiment = client.get_experiment_by_name(EXPERIMENT)
runs = client.search_runs(
    [experiment.experiment_id],
    filter_string="tags.sweep = 'hidden-lr-v1'",
    order_by=["metrics.best_val_acc DESC", "metrics.best_val_loss ASC"],
)
for r in runs:
    print(r.info.run_name, r.data.params["hidden"], r.data.params["lr"],
          round(r.data.metrics["best_val_acc"], 3))
best_run = runs[0]

With 50 validation graphs and one seed, small differences between rows are noise. Repeat with several seeds before preferring a configuration.

Reload the best run and test it once

Parameters come back as strings, so convert them before rebuilding the model. Check that the restored weights reproduce the logged validation accuracy, then evaluate the test graphs for the selected run only:

python
params = best_run.data.params
restored = make_model(int(params["hidden"]))
weights = mlflow.artifacts.download_artifacts(
    run_id=best_run.info.run_id, artifact_path="best_model.pt", dst_path="recovered")
restored.load_state_dict(torch.load(weights, weights_only=True))

check = tgx.evaluate(restored, val_loader, nn.CrossEntropyLoss(),
                     metrics={"acc": tgx.accuracy}, device="cpu")
assert abs(check["acc"] - best_run.data.metrics["best_val_acc"]) < 1e-6

test = tgx.evaluate(restored, test_loader, nn.CrossEntropyLoss(),
                    metrics={"acc": tgx.accuracy}, device="cpu")
client.log_metric(best_run.info.run_id, "test_acc", test["acc"])
print("test accuracy of the selected run:", round(test["acc"], 3))

MLflow also has a PyTorch flavour (mlflow.pytorch) for packaging whole models. A state_dict plus logged parameters is enough to rebuild the model here.

Mark failed runs as failed

This is a trap in 1.5.1: when an exception leaves a with MLflowLogger(...) block, the run is closed with status FINISHED. MLflow's own with mlflow.start_run() would mark it FAILED. Until that changes, set the status yourself:

python
try:
    with MLflowLogger(run_name="will_fail", experiment=EXPERIMENT,
                      tracking_uri=TRACKING_URI) as run:
        failed_id = run.run_id
        try:
            raise RuntimeError("simulated crash during training")
        except BaseException:
            mlflow.end_run(status="FAILED")
            raise
except RuntimeError as err:
    print("training stopped:", err)

assert mlflow.get_run(failed_id).info.status == "FAILED"

What the environment record contains

Two different dictionaries are available, and neither is a full lock file:

python
print(sorted(seed_state))
# ['backend_settings', 'cuda_available', 'cuda_device_count', 'deterministic',
#  'seed', 'torch_version']
print(sorted(reproducibility_report()))
# ['cuda_available', 'cuda_device_count', 'cudnn_benchmark', 'cudnn_deterministic',
#  'python_hash_seed', 'python_version', 'torch_version', 'use_deterministic_algorithms']

Neither contains the hostname, GPU name, CUDA version, installed packages or a git commit. If you need those, log them yourself, for example with mlflow.set_tag(...); for the git commit, MLflow may already have tagged the run (see Limitations). The GNN reproducibility guide covers the rest.

Open the web UI

The UI needs the full mlflow package; the mlflow-skinny distribution used to test this page cannot start it, so neither command below was run. To browse the runs this tutorial wrote to its throwaway file store, start the UI from the folder that contains mlruns_demo:

bash
MLFLOW_ALLOW_FILE_STORE=true mlflow ui --backend-store-uri ./mlruns_demo

If you switched TRACKING_URI to the recommended database store, use this instead:

bash
mlflow ui --backend-store-uri sqlite:///mlflow.db

Then open http://127.0.0.1:5000, select runs and use Compare.

Limitations

  • MLflowLogger is a thin adapter: it has no methods for parameters, artifacts, tags after start, nested runs or model registration. Use mlflow directly for those.
  • TGraphX does not pin an MLflow version beyond >=2.0. Behaviour such as the default store differs between major versions, so record the version you used.
  • A run started from a script that lives in a git repository gets an mlflow.source.git.commit tag automatically, plus branch and repository URL tags where available. Notebooks and code outside a repository may not get one, and the tag names the last commit, so uncommitted changes are not captured. Log the code version yourself in those cases.
  • Run names are not unique. Identify runs by run_id.
  • For a team or many concurrent jobs, use a tracking server with a database rather than local files.

Frequently asked questions

Do I need an MLflow server? No. A single user can work against a local SQLite database. A server is for sharing runs.

Can I keep tracking without MLflow? Yes. tgx.CSVLogger writes metrics.csv, which the TGraphX dashboard can show and export as offline HTML.

How do I log the architecture? mlflow.log_text(str(model), "model.txt") stores it as an artifact.

How do I delete a run? mlflow.MlflowClient().delete_run(run_id) marks it deleted; restore_run brings it back.

Per-epoch metrics or only final values? Both: per-epoch series show instabilities, final values make sorting easy.

Related guides