TGraphX › Insights › TGraphX Dashboard: Offline HTML Reports for GNN Experiments
← Back to Insights

TGraphX Dashboard: Offline HTML Reports for GNN Experiments

Topic: APIs, tooling and research-engineering workflow

When a collaborator asks which settings produced last week's best run, the answer should not be scattered across terminal output and notebook cells. The TGraphX dashboard (tgraphx.dashboard) reads the files in a run directory and shows them in two ways: a local web server you can watch during training, and a single offline HTML snapshot you can attach to an issue, a pull request or a paper's supplement.

The dashboard is read-only and collects nothing by itself. It shows what your training script writes, so this guide covers both halves: writing the run files, then viewing and exporting them. The Python examples were tested with TGraphX 1.5.1 on CPU.

If you used an earlier version of this page: it described a DashboardReporter object. TGraphX 1.5.1 has no such class; use the workflow below.

Why offline HTML reports

Hosted trackers and tracking servers are useful when you can reach them. On an HPC node without outbound internet, in an isolated environment, or when a reviewer should not need an account, a file that opens in a browser is simpler. The exported snapshot embeds its CSS, JavaScript and data, so it needs no server and no CDN.

It does not replace a tracking system: it is a snapshot of one run directory at the moment you export it.

What the dashboard reads

File in the run directory Shown as Written with
metrics.csv line charts and the metrics table CSVLogger
run_metadata.json the Config page; run name and status in the live view write_run_metadata
graph_stats.json precomputed graph statistics write_graph_stats
graph_metadata.json graph section (optional) your own JSON

Two details matter. Charts need an epoch or step column for the x-axis. And hyperparameters appear only if you put them in run_metadata.json; the exported snapshot does not read an experiment_config.json file. The live server additionally reads a number of optional report files (for mining, knowledge graphs, sampling and so on) that the exported snapshot does not include.

Nothing is captured automatically: no model summary, no hyperparameters, no graph description.

Step 1: build a small problem to log

A synthetic node classification graph with a clean 60/20/20 split:

python
import os

import torch
import torch.nn as nn
import torch.nn.functional as F

import tgraphx as tgx
from tgraphx import CSVLogger, GCNConv, Graph, write_graph_stats, write_run_metadata
from tgraphx.estimators import node_train_val_test_split
from tgraphx.metrics import precision_recall_f1

tgx.set_seed(0)
num_nodes, num_classes, in_dim = 300, 3, 16
y = torch.randint(0, num_classes, (num_nodes,))
x = 0.35 * torch.randn(num_classes, in_dim)[y] + torch.randn(num_nodes, in_dim)
cand = torch.randint(0, num_nodes, (2, 3000))
keep = (y[cand[0]] == y[cand[1]]) | (torch.rand(3000) < 0.3)
keep &= cand[0] != cand[1]

train_mask, val_mask, test_mask = node_train_val_test_split(num_nodes, 0.6, 0.2, 0.2, seed=0)
g = Graph(node_features=x, edge_index=cand[:, keep], node_labels=y,
          train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
g.make_undirected()

Step 2: train and write the run files

The function below writes the metadata and graph statistics before training, one CSV row per epoch during training, and the final summary afterwards. Validation picks the best epoch, and the test nodes are evaluated once with those weights.

python
import copy


class GCN(nn.Module):
    def __init__(self, hidden):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden)
        self.conv2 = GCNConv(hidden, num_classes)

    def forward(self, x, edge_index):
        h = F.dropout(F.relu(self.conv1(x, edge_index)), p=0.5, training=self.training)
        return self.conv2(h, edge_index)


def run_experiment(run_dir, hidden, lr=0.01, seed=0, epochs=60):
    if os.path.exists(f"{run_dir}/metrics.csv"):
        raise FileExistsError(f"{run_dir} already has metrics; use a new directory")
    tgx.set_seed(seed)
    model = GCN(hidden)
    opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=5e-4)

    meta = {"run_name": os.path.basename(run_dir), "status": "running",
            "task": "node_classification", "device": "cpu", "seed": seed,
            "epochs": epochs, "total_epochs": epochs, "tgraphx_version": tgx.__version__,
            "model": "2-layer GCN", "hidden": hidden, "lr": lr,
            "data": "synthetic, 3 classes", "split": "nodes 60/20/20, seed 0"}
    write_run_metadata(f"{run_dir}/run_metadata.json", **meta)

    degree = torch.bincount(g.edge_index[1], minlength=g.num_nodes)
    write_graph_stats(
        {"num_nodes": g.num_nodes, "num_edges": g.num_edges,
         "avg_degree": degree.float().mean().item(),
         "min_degree": int(degree.min()), "max_degree": int(degree.max()),
         "isolated_nodes": int((degree == 0).sum())},
        f"{run_dir}/graph_stats.json",
    )

    best_val, best_epoch, best_state = -1.0, -1, None
    with CSVLogger(run_dir) as log:
        for epoch in range(epochs):
            model.train()
            opt.zero_grad()
            loss = F.cross_entropy(model(g.x, g.edge_index)[g.train_mask], g.y[g.train_mask])
            loss.backward()
            opt.step()

            model.eval()
            with torch.no_grad():
                logits = model(g.x, g.edge_index)[g.val_mask]
            target = g.y[g.val_mask]
            scores = precision_recall_f1(logits.argmax(1), target, num_classes=num_classes)
            val_acc = (logits.argmax(1) == target).float().mean().item()

            # Log every key from the first row: CSVLogger fixes the header there
            log.log(epoch=epoch,
                    train_loss=loss.item(),
                    val_loss=F.cross_entropy(logits, target).item(),
                    val_accuracy=val_acc,
                    val_macro_f1=scores["f1"],
                    **{f"val_f1_class{c}": v for c, v in enumerate(scores["f1_per_class"])})

            if val_acc > best_val:
                best_val, best_epoch = val_acc, epoch
                best_state = copy.deepcopy(model.state_dict())

    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        pred = model(g.x, g.edge_index).argmax(1)
    test_acc = (pred[g.test_mask] == g.y[g.test_mask]).float().mean().item()

    meta.update(status="completed", best_metric=best_val, best_epoch=best_epoch,
                test_accuracy=test_acc)
    write_run_metadata(f"{run_dir}/run_metadata.json", **meta)
    return meta


for hidden in (16, 64):
    summary = run_experiment(f"runs/gcn_h{hidden}", hidden)
    print(summary["run_name"], "best val accuracy", round(summary["best_metric"], 3))

Three habits are worth copying from this code:

  • One directory per run. CSVLogger appends to an existing metrics.csv, so reusing a directory mixes two runs.
  • A stable set of columns. Keys that first appear after the first row are dropped without an error.
  • Plain Python numbers. Call .item() on tensors; the JSON writers store other objects as strings.

write_run_metadata replaces the file each time, which is why the full dictionary is passed again at the end.

Step 3: export an offline HTML snapshot

python
from tgraphx.dashboard.app import export_dashboard_html

os.makedirs("reports", exist_ok=True)      # the output folder must exist
for name in ("gcn_h16", "gcn_h64"):
    export_dashboard_html(f"runs/{name}", f"reports/{name}.html")
    print(name, os.path.getsize(f"reports/{name}.html") // 1024, "KB")

For this small example each file came to a little under 150 KB, most of it the embedded stylesheet and script. Size grows with the number of logged rows and columns; the export keeps at most the latest 5000 rows.

The same export from the command line, without writing Python:

bash
tgraphx-dashboard --logdir runs/gcn_h16 --export-html reports/gcn_h16.html

The snapshot holds the charts, the log table, run_metadata.json and the graph statistics as they were at export time. In the exported file, use the Metrics, Graph, Logs and Config pages. The Overview status card reads "unknown" and the Hardware and Mining pages have no data, because those are filled by the live server; the status you wrote is on the Config page. The charts offer hover values, optional smoothing and CSV/SVG downloads.

The file contains no model weights; save those separately with tgx.save_checkpoint. Open the file and check what it contains before sharing it, because everything you wrote into the metadata, including local paths or notes, goes along.

Watch a run live

Start the server in a second terminal while training writes to the run directory:

bash
tgraphx-dashboard --logdir runs/gcn_h16 --port 8765

Then open http://127.0.0.1:8765. The page refreshes itself. From Python, launch_dashboard(logdir) blocks until interrupted, and launch_dashboard_background runs the server in a thread:

python
import json
import urllib.request

from tgraphx.dashboard import launch_dashboard_background

server = launch_dashboard_background("runs/gcn_h16", port=0, verbose=False)   # 0: any free port
url = f"http://127.0.0.1:{server.server_address[1]}"
with urllib.request.urlopen(f"{url}/api/status") as response:
    print(url, json.load(response)["status"])

server.shutdown()
server.server_close()

Compare several runs

There is no built-in HTML comparison page. You have two real options.

Switch between runs in the live view. Point --logdir at a parent folder such as runs/ whose subfolders each contain metrics.csv. A drop-down switches the metric charts between runs. The metadata and graph panels are read from the parent folder itself, not from the selected run.

Make a summary table. tgraphx-report collects every folder with a run_metadata.json below a parent directory into a Markdown table and, optionally, CSV. Its columns include run_name, seed, epochs, best_metric, best_epoch and the final training loss, which is why the metadata above uses those names. It does not include test_accuracy or your hyperparameters.

bash
tgraphx-report runs --output reports/summary.md --csv reports/summary.csv

From Python, summarize_runs returns every metadata field. Choose on the validation column and only then read the test number of the chosen run:

python
from tgraphx.experiments import summarize_runs, write_markdown_report

write_markdown_report("runs", "reports/summary.md")
rows = summarize_runs("runs")
chosen = max(rows, key=lambda row: row["best_metric"])
print("chosen:", chosen["run_name"], "test accuracy:", round(chosen["test_accuracy"], 3))

A single seed per configuration, as here, is not enough to say that one is better. Repeat with several seeds.

Sharing and security

  • The server binds to 127.0.0.1 by default. Binding to another address requires --token, and clients that are not local must then send it with each API request.
  • In 1.5.1 the web page does not pass a ?token= value on to its own data requests, so a browser on another machine loads the layout but no data. In a local simulation of such a client, every data request was rejected.
  • For a remote machine, keep the default binding and forward the port over SSH: ssh -L 8765:127.0.0.1:8765 user@host, then open http://127.0.0.1:8765.
  • The server speaks plain HTTP, so do not expose it to untrusted networks. The export never embeds the token.

Limitations

  • Snapshot, not streaming. An export reflects the files at that moment. If a job dies, the rows already written remain and you can still export them; the status stays running unless you update it.
  • No versioning. Exporting to the same path overwrites the file.
  • No database. For querying hundreds of runs, use a tracking system; the MLflow logger tutorial shows the built-in adapter.
  • No images or free-form attachments. The snapshot is built from the run files listed above. Keep figures and notes next to the report, or add short notes as metadata fields.

Version control

Committing a small report next to the code that produced it gives collaborators a record they can open. Put the commit hash into run_metadata.json so the link works in both directions, and avoid committing many large reports to the same repository.

Frequently asked questions

Can I export without a training loop? Yes. Any directory with a metrics.csv or run_metadata.json can be exported, whatever produced the files.

Why are my charts empty? Check that metrics.csv is directly inside --logdir, that it has an epoch or step column, and that the values are numbers. The export does not read subfolders.

Is there a way to check a run folder before sharing it? tgx.audit_run_dir(path) reports which of its expected files are present and whether the JSON parses. It expects run_metadata.json, metrics_summary.json and benchmark_summary.json, so it lists the last two as missing for the folders above unless you add them with tgx.write_metrics_summary and tgx.write_benchmark_results. It does not judge the science.

Related guides