TGraphX › Insights › Mini-Batch Training Loop for [C, H, W] Node Features in TGraphX
← Back to Insights

Mini-Batch Training Loop for [C, H, W] Node Features in TGraphX

Topic: Getting started with TGraphX

The getting started tutorial introduces tensor-valued nodes and the one-call helpers. This one goes one level down and writes the node classification workflow by hand: a kNN graph over image-like nodes, a checked train/validation/test split, a mini-batch loop with NeighborLoader, early stopping on validation loss, and saved artifacts.

Setup

bash
pip install tgraphx

You need Python 3.10 or newer and PyTorch 1.13 or newer. Everything here runs on CPU and was tested with TGraphX 1.5.1.

python
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.reproducibility import set_seed, reproducibility_report

print(tgx.__version__)  # 1.5.1
set_seed(0, deterministic=True)

Seed before you create data or models, not after.

Step 1: Build the graph

We use 400 nodes, each a [3, 8, 8] patch. The data is synthetic: each class shifts the three channels by its own small offset, and every pixel carries noise, so there is something to learn.

python
from tgraphx.estimators import node_train_val_test_split

N, num_classes = 400, 4
node_shape = (3, 8, 8)

y = torch.randint(0, num_classes, (N,))
channel_offsets = torch.randn(num_classes, 3, 1, 1)
x = 0.3 * channel_offsets[y] + torch.randn(N, *node_shape)

# kNN on the features; the helper flattens only to compute similarity
edge_index = tgx.knn_graph(x, k=8, metric="cosine", make_symmetric=True)

train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=0)

g = tgx.Graph(x=x, edge_index=edge_index, y=y,
              train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
print(g.num_nodes, g.feature_shape, g.num_edges)

The graph is built from the features of all nodes, including validation and test nodes. That is the usual transductive setting and uses no labels. If test nodes must be unknown at training time, build the training graph from training nodes only.

Step 2: Validate the graph and the split

python
g.validate()  # the constructor's checks again (masks are not re-checked)
tgx.validate_graph(g, strict=True, check_finite=True)  # adds NaN/Inf and mask lengths
tgx.assert_tensor_native(g, min_rank=3)  # fails if the features were flattened

tgx.check_leakage(train_mask=g.train_mask, val_mask=g.val_mask,
                  test_mask=g.test_mask, strict=True)

The Graph constructor already rejects out-of-range edge indices. After modifying a graph in place, call g.validate(), which re-runs the constructor's index range, dtype, device and length checks (not mask lengths). tgx.validate_graph() is a lighter report: it misses negative indices and wrong-length edge weights or labels. Use it for check_finite=True, which looks for NaN/Inf in node and edge features, and for mask lengths.

Always call check_leakage with keyword arguments and boolean masks. Its first positional parameter is a graph, so passing three masks positionally shifts them all and can report a clean result for overlapping splits. It checks node-mask overlap only.

Step 3: Build a model

python
from tgraphx import build_model

def make_model():
    return build_model(
        task="node_classification",
        layer="sage",              # TensorGraphSAGELayer
        in_shape=node_shape,       # (C, H, W)
        hidden_shape=(8, 8, 8),
        num_layers=2,
        num_classes=num_classes,
    )

model = make_model()
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
print(model(g.x[:4], torch.tensor([[0, 1], [2, 3]])).shape)  # torch.Size([4, 4])

You choose the layer type with layer=; it is not inferred from in_shape. Check the spelling of keyword arguments, because unknown ones are silently ignored.

Know what the choice means for tensor data. "sage", "gat" and "gin" use 1×1 convolutions, which never mix pixel positions, and the factory averages over the spatial axes before the final linear layer. Such a model cannot see spatial arrangement: shuffling the pixels the same way in every node leaves its output unchanged.

python
perm = torch.randperm(8 * 8)
shuffled = g.x.flatten(2)[:, :, perm].view_as(g.x)
with torch.no_grad():
    assert torch.allclose(model(g.x, g.edge_index),
                          model(shuffled, g.edge_index), atol=1e-5)

That is fine for this synthetic task, where the class signal is in the channel values. If arrangement matters, use layer="conv" (ConvMessagePassing, which adds 3×3 convolutions and costs more).

Step 4: Mini-batch training with NeighborLoader

tgx.fit() is not the tool here: it ignores node masks and does not accept the batches a NeighborLoader produces. The loop is short enough to write yourself.

python
from tgraphx import NeighborLoader

def train_one_epoch(epoch):
    loader = NeighborLoader(
        g, fanouts=[10, 5],     # sample up to 10 in-neighbors at hop 1, 5 at hop 2
        mask=g.train_mask,      # seed nodes: training nodes only
        batch_size=64, shuffle=True, seed=epoch,
    )
    model.train()
    total, count = 0.0, 0
    for batch in loader:
        logits = model(batch.node_features, batch.edge_index)
        loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)
        opt.zero_grad()
        loss.backward()
        opt.step()
        total += loss.item() * batch.batch_size
        count += batch.batch_size
    return total / count

@torch.no_grad()
def evaluate_nodes(mask):
    model.eval()
    loader = NeighborLoader(g, fanouts=[-1, -1], mask=mask,  # all neighbors
                            batch_size=128, shuffle=False)
    loss, correct, count = 0.0, 0, 0
    for batch in loader:
        out = batch.seed_logits(model(batch.node_features, batch.edge_index))
        loss += F.cross_entropy(out, batch.seed_y, reduction="sum").item()
        correct += int((out.argmax(1) == batch.seed_y).sum())
        count += batch.batch_size
    return loss / count, correct / count

Four details matter:

  • mask=None would make every node a seed, validation and test included. g.train_mask is never picked up automatically.
  • A batch also contains non-seed neighbors. Use batch.seed_logits() and batch.seed_y so the loss sees training labels only.
  • fanouts limits the sampling step only: the batch keeps every edge among the sampled nodes, so a node can receive more messages than its fanout.
  • In 1.5.1 neighbor sampling creates a new random generator on every call, so the same batch of seeds draws the same neighbors each time. Rebuilding the loader with seed=epoch changes the draw between epochs.

With two layers and fanouts=[-1, -1], every neighbor that can influence a seed node is in its batch, so for this model the mini-batch evaluation matches a full-graph forward pass:

python
model.eval()
batch = next(iter(NeighborLoader(g, fanouts=[-1, -1], mask=g.val_mask,
                                 batch_size=32, shuffle=False)))
with torch.no_grad():
    full = model(g.x, g.edge_index)
    sampled = batch.seed_logits(model(batch.node_features, batch.edge_index))
assert torch.allclose(sampled, full[batch.seed_node_ids], atol=1e-5)

Now train, keep the weights and optimizer state from the epoch with the best validation loss, and look at the test set once:

python
import copy
from tgraphx.estimators import EarlyStopping

stopper = EarlyStopping(patience=5, mode="min")  # the default mode is "max"
best_val, best_epoch = float("inf"), -1
best_state, best_opt_state = None, None

for epoch in range(20):
    train_loss = train_one_epoch(epoch)
    val_loss, val_acc = evaluate_nodes(g.val_mask)
    if val_loss < best_val:
        best_val, best_epoch = val_loss, epoch
        best_state = {k: v.clone() for k, v in model.state_dict().items()}
        best_opt_state = copy.deepcopy(opt.state_dict())  # Adam updates in place
    if stopper.step(val_loss):
        break

model.load_state_dict(best_state)
opt.load_state_dict(best_opt_state)  # same epoch as the weights
test_loss, test_acc = evaluate_nodes(g.test_mask)
print(f"best epoch {best_epoch}  val loss {best_val:.3f}  test accuracy {test_acc:.3f}")

The number printed describes this synthetic problem only. For real data, compare against a baseline that ignores the graph and one that uses flattened features.

Step 5: Save the experiment

python
import json

g.save("runs/deep/graph.tgx")   # rank-4 features, labels and masks
tgx.save_checkpoint(model, opt, best_epoch, "runs/deep/best.pt", val_loss=best_val)
tgx.write_metrics_summary("runs/deep/metrics_summary.json",
                          best_epoch=best_epoch, val_loss=best_val,
                          test_accuracy=test_acc)
with open("runs/deep/reproducibility.json", "w") as f:
    # The report holds versions and determinism flags but no seeds: add them
    json.dump({**reproducibility_report(),
               "seed": 0,              # set_seed
               "split_seed": 0,        # node_train_val_test_split
               "loader_seed": "epoch"  # NeighborLoader(seed=epoch) in training
               }, f, indent=2)

# Reload and confirm the restored model gives the same test accuracy
saved_graph = tgx.Graph.load("runs/deep/graph.tgx")
assert torch.equal(saved_graph.x, g.x) and torch.equal(saved_graph.test_mask, g.test_mask)

restored = make_model()
restored_opt = torch.optim.Adam(restored.parameters(), lr=1e-2)
epoch_loaded = tgx.load_checkpoint(restored, restored_opt, "runs/deep/best.pt",
                                   map_location="cpu")
model, opt = restored, restored_opt  # resume from epoch best_epoch + 1
assert epoch_loaded == best_epoch
assert evaluate_nodes(g.test_mask)[1] == test_acc

.tgx files are unpickled on load, so only open files you trust. Pass plain Python numbers to the writer functions: a tensor would be stored as a string.

Step 6: Reproducibility

set_seed(0, deterministic=True) at the top seeds Python, NumPy and PyTorch, sets the cuDNN flags and requests deterministic algorithms. Because it uses warn-only mode by default, an operation without a deterministic implementation warns instead of failing, so do not assume bit-for-bit equality, especially on GPUs or across machines and library versions. Nothing writes a reproducibility report for you; Step 5 saved one explicitly. reproducibility_report() records versions, CUDA information, determinism flags and PYTHONHASHSEED, but not the seed you passed to set_seed or any other seed, so Step 5 added them by hand. The split seed decides which nodes are held out, and the loader seeds control shuffling and neighbor choice.

Common mistakes

Mixing vector-only layers with tensor inputs. GCNConv, GATv2Conv and APPNP expect [N, D] input. Use build_model(..., layer="sage") or another tensor layer for [N, C, H, W] features.

kNN on a very large graph. tgx.knn_graph compares all pairs, so its time grows as O(N²). Precompute neighbors with an approximate nearest-neighbor tool for large N.

Evaluating on sampled neighborhoods without saying so. Limited fanouts at test time make the score depend on the sample. Use all neighbors, or report the fanouts.

Assuming tensor features improve accuracy by default. They keep spatial structure available to the model. Whether that helps depends on the task, so benchmark against a flat-vector baseline.


FAQ

Q: How does NeighborLoader handle tensor-valued node features?
A: It samples using edge_index only and then slices the first dimension of node_features, so each node keeps its shape. The graph and its features stay in host memory; to keep node features on disk instead, pass a feature_store= as shown in the memory-mapped feature store guide.

Q: What about Cluster-GCN?
A: It is a different way to form mini-batches: partition the nodes, then train on the induced subgraph of one or a few parts with ClusterLoader. RandomBalancedPartitioner splits nodes at random, ignoring connectivity; BFS and spectral partitioners are also available. See GraphSAINT and Cluster-GCN in TGraphX.

Q: Can I export to GraphML?
A: The structure, yes. Features are written only for vector features and only if you pass include_tensor_features=True to write_graphml; by default the call succeeds and silently leaves out node and edge features. For [N, C, H, W] features use .tgx.

Q: What happens if validation fails?
A: tgx.validate_graph(g, strict=True) raises GraphValidationError, a subclass of ValueError. Without strict, it returns a dictionary with ok, issues and info. g.validate() raises TypeError or ValueError instead.